﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace Project_ScansiaPacific
{
    public partial class FrKV2_XP : DevComponents.DotNetBar.Office2007Form
    {
        public FrKV2_XP()
        {
            InitializeComponent();
            //Sender = new SendMessage(GetMessage);
        }
        private void Enable()
        {
            tab_Nhap.Visible = true;
            //tab_Xuat.Visible = true;
        }
        private void Disable()
        {
            tab_Nhap.Visible = false;
           // tab_Xuat.Visible = false;
        }
        private void Check_User()
        {
            Process prs = new Process();
            SqlConnection Conn = prs.Connect();
            SqlCommand cmd = new SqlCommand();
            try
            {
                Conn.Open();
                string check = @"select GroupUser from dbo.Users where UsersName='" + lb_user.Text + "'";
                cmd.Connection = Conn;
                cmd.CommandText = check;
                //MessageBox.Show(check);
                check = cmd.ExecuteScalar().ToString();
                if (check == "thongke" || check == "admin" || check == "nhaplieu")
                    Enable();
                else
                    Disable();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                Conn.Close();
                cmd.Dispose();
            }
        }
        private string MaSP1, TenSP1, MaCT1, TenCT1, SoBB1, SoKH1, Serial1, SLXuat1, Ngay_start1, Ngay_End1, child = " - ", Ngay1, NgayInsert1, UserXuat, GhiChu1, flag1, SoXe1,string_temp,LyDo1,SoPhieu1,SLNhap1;
        private double Tong1 = 0, SLXuat_d = 0,SLtemp_d,SLNhap_d=0,SLKH_N=0;
        private int i, j, k;
        private void combo_load()
        {
            Data dta = new Data();
            FormProcess Frp = new FormProcess();
            SqlConnection Conn = dta.Connect();
            DataSet ds = new DataSet();
            Conn.Open();
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = Conn;
            cmd.CommandText = @"select * from dbo.Load_cbSP";
            try
            {
                SqlDataReader rd = cmd.ExecuteReader();
                while (rd.Read())
                {
                    cb_MaSPoutput.Items.Add(rd[1].ToString() + " - " + rd[0].ToString());
                    cb_MaSP.Items.Add(rd[1].ToString() + " - " + rd[0].ToString());
                    cb_MaSPReport.Items.Add(rd[1].ToString() + " - " + rd[0].ToString());
                    cb_MaSP_C.Items.Add(rd[1].ToString() + " - " + rd[0].ToString());
                    cb_MaSP_N.Items.Add(rd[1].ToString() + " - " + rd[0].ToString());
                }
                string_temp = @"select dbo.Load_CTSP_Mua.MaSP,dbo.Load_CTSP_Mua.TenChiTiet+' - '+dbo.Load_CTSP_Mua.MaChiTiet from dbo.Load_CTSP_Mua inner join dbo.ChiTiet_KhuVuc on ChiTiet_KhuVuc.MaCT=dbo.Load_CTSP_Mua.MaChiTiet and (ChiTiet_KhuVuc.KhuVuc='KV2XP' or ChiTiet_KhuVuc.KhuVuc='KV3' or ChiTiet_KhuVuc.KhuVuc='KV2XLR') group by dbo.Load_CTSP_Mua.MaSP,dbo.Load_CTSP_Mua.TenChiTiet+' - '+dbo.Load_CTSP_Mua.MaChiTiet";
                ds = dta.dts(string_temp);
                for (i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    dataGridView_LoadSP.Rows.Add(ds.Tables[0].Rows[i][0].ToString(), ds.Tables[0].Rows[i][1].ToString());
                }
                ds.Clear();
                ds.Clone();
                string_temp = @"SELECT  Load_CTSP_Mua.[MaSP],Load_CTSP_Mua.TenSP
                                ,[MaCT],Load_CTSP_Mua.TenChiTiet
                                ,[ID_link]
                                ,[SLCT_QuyDoi]
                                ,[KhuVuc]
                            FROM [dbo].[ChiTiet_KhuVuc] inner join Load_CTSP_Mua on Load_CTSP_Mua.MaChiTiet=ChiTiet_KhuVuc.MaCT and ChiTiet_KhuVuc.KhuVuc like '%KV2XLR%'";
                            

                ds = dta.dts(string_temp);
                dataGridView2.DataSource = ds.Tables[0];
                string[] arr = new string[] { "Xuat Rap","KV3_Bo sung hang loai","KV4_Bo sung hang loai","Khác" };
                for (i = 0; i < arr.Length; i++)
                {
                    cb_LyDoXuat.Items.Add(arr[i].ToString());
                   
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                cmd.Dispose();
                Conn.Close();
            }
           // dataGridView1.Columns["SoLuongXuat"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
           
        }

        private void cb_MaSPoutput_SelectedIndexChanged(object sender, EventArgs e)
        {
            Process prs = new Process();

            MaSP1 = prs.substring_right(cb_MaSPoutput.Text, child);
            cb_MaCToutput.Items.Clear();
     
            cb_MaCToutput.Text = "";
            for (i = dataGridView_LoadSP.Rows.Count - 2; i >= 0; i--)
            {
                if (MaSP1 == dataGridView_LoadSP.Rows[i].Cells[0].Value.ToString())
                {
                    cb_MaCToutput.Items.Add(dataGridView_LoadSP.Rows[i].Cells[1].Value.ToString());
                }
            }
            
            
        }
        private void KHXuongPhieu()
        {
            Process prs = new Process();
            FormProcess Frp = new FormProcess();
            SqlConnection Conn = prs.Connect();
            SqlCommand cmd = new SqlCommand();
           
            try
            {
                cb_SoKHoutput.Items.Clear();
                cb_SoKHoutput.Text = "";
                Conn.Open();
                cmd.Connection = Conn;
                MaCT1 = prs.substring_right(cb_MaCToutput.Text, child);

                GhiChu1 = @"select left(ID_KeHoach,5),ID from KH_TheoDoi where SLTheoDoi>0.01*SLKH and MaCT='" + MaCT1 + "' and ID_KeHoach like '%KV2XP%'";
                Frp.cb1(cb_SoKHoutput, GhiChu1, 0, 1);
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
                //lb_TonKho.Text = "0";
            }
            finally
            {
                Conn.Close();
                cmd.Dispose();
            }
        }
        private void cb_MaCToutput_SelectedIndexChanged(object sender, EventArgs e)
        {
            KHXuongPhieu();
        }

        private void cb_SoKHoutput_Leave(object sender, EventArgs e)
        {
            FormProcess Frp = new FormProcess();
            Process prs = new Process();
            SqlConnection Conn = prs.Connect();
            Conn.Open();
            SqlCommand cmd = new SqlCommand();
            try
            {
                SoKH1 = prs.substring_right(cb_SoKHoutput.Text, child);
                string check_SL = null;
                check_SL = @"select SLTheoDoi from dbo.KH_TheoDoi where ID='" + SoKH1 + "'";
                cmd.CommandText = check_SL;
                cmd.Connection = Conn;
                lb_SLKHoutput.Text = cmd.ExecuteScalar().ToString();
            }
            catch
            {
                //MessageBox.Show(ex.Message);
                cb_SoKHoutput.Text = "";
                lb_SLKHoutput.Text = "0";
            }
            finally
            {
                Conn.Close();
                cmd.Dispose();
            }
        }

        private void txt_SLoutput_Leave(object sender, EventArgs e)
        {
            FormProcess Frp = new FormProcess();
            Frp.checktext_number(txt_SLoutput);
        }
        private void add_grid_out()
        {
            SqlCommand cmd = new SqlCommand();
            SqlConnection Conn = new SqlConnection();
            Process prs = new Process();
            Conn = prs.Connect();
            Conn.Open();
            cmd.Connection = Conn;
            try
            {

                TenSP1 = prs.substring_left(cb_MaSPoutput.Text, child);
                TenCT1 = prs.substring_left(cb_MaCToutput.Text, child);
                MaCT1 = prs.substring_right(cb_MaCToutput.Text, child);
                if (TenSP1 == "" || MaCT1 == "" || txt_Ngayoutput.Text == "" || txt_SLoutput.Text == "" || txt_SoBBoutput.Text == "" || txt_Serial.Text == "")
                {
                    MessageBox.Show("Thông Tin Nhập Không Chính Xác Hoặc Thiếu");
                }
                else
                {
                    i = 0;
                    if (dataGridView1.Rows.Count > 1)
                    {
                        while (i < dataGridView1.Rows.Count - 1)
                        {
                            if (MaCT1 != dataGridView1.Rows[i].Cells["MaCTXuat"].Value.ToString())
                                i++;
                            else
                                break;
                        }
                    }
                    if (dataGridView1.Rows.Count == 1 || i == dataGridView1.Rows.Count - 1)
                    {
                        k = cb_MaCToutput.Items.Count - 1;
                        while (k >= 0)
                        {

                            if (MaCT1 == prs.substring_right(cb_MaCToutput.Items[k].ToString(), child))
                                break;
                            else
                                k--;
                        }
                        j = cb_SoKHoutput.Items.Count - 1;
                        SoKH1 = prs.substring_right(cb_SoKHoutput.Text, child);
                        while (j >= 0)
                        {
                            // MessageBox.Show(prs.substring_right(cb_SoKHoutput.Items[j].ToString(),child));
                            if (SoKH1 == prs.substring_right(cb_SoKHoutput.Items[j].ToString(), child))
                                break;
                            else
                                j--;
                        }

                        // MessageBox.Show(j.ToString());
                        if (k >= 0 && j >= 0)
                        {
                            SoBB1 = (double.Parse(txt_SoBBoutput.Text)).ToString();
                            SoXe1 = txt_SoXeoutput.Text;
                            Serial1 = txt_Serial.Text;
                            Ngay1 = txt_Ngayoutput.Text.Trim();
                            SLXuat1 = txt_SLoutput.Text;
                            string[] temp = txt_Ngayoutput.Text.Split('/');
                            NgayInsert1 = temp[1] + "/" + temp[0] + "/" + temp[2];
                            GhiChu1 = txt_GhiChuoutput.Text;
                            dataGridView1.Rows.Add(TenSP1, MaCT1, TenCT1, SoKH1, Serial1, SLXuat1, Ngay1, NgayInsert1, SoBB1, SoXe1, GhiChu1, "0");

                            j = dataGridView1.Rows.Count - 1;

                            dataGridView1.CurrentCell = dataGridView1.Rows[j].Cells[0];
                            dataGridView1.FirstDisplayedCell = dataGridView1.Rows[j].Cells[0];
                            prs.formatcolordatagrid(dataGridView1);
                            //prs.reset_txt(groupPanel1);
                            txt_SLoutput.Text = "";
                            cb_MaCToutput.Text = "";
                            txt_GhiChuoutput.Text = "";
                            Tong1 = double.Parse(lb_TongXuat.Text);
                            Tong1 += double.Parse(SLXuat1);
                            lb_TongXuat.Text = Tong1.ToString();
                            lb_TongXuat.Text = string.Format("{0:###,###}", Tong1);
                            lb_SLKHoutput.Text = "0";
                            //lb_KHDP.Text = "0";
                            txt_Serial.Focus();
                            cb_SoKHoutput.Text = "";
                            txt_SoBBoutput.Text = (double.Parse(txt_SoBBoutput.Text) + 1).ToString();
                            txt_SoXeoutput.Text = "";
                            txt_Serial.Text = "";
                        }
                        else
                            MessageBox.Show("Kiểm tra lại Mã CT hoặc Mã KH nhập");
                    }
                    else
                        MessageBox.Show("Chi Tiết này đã có trong DS phía dưới");
                }
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                Conn.Close();
                cmd.Dispose();
            }
        }

        private void bt_insertoutput_Click(object sender, EventArgs e)
        {
            add_grid_out();
        }

        private void bt_editoutput_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Phần mềm không hỗ trợ chức năng này, bạn có thể xóa dữ liệu sai, sau đó thêm mới");
        }
        private void save_output()
        {
            int i;
            Data dta = new Data();
            SqlConnection Conn = dta.Connect();
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "Tran_Ins_Up_XP";
            cmd.CommandType = CommandType.StoredProcedure;
            Conn.Open();
            cmd.Connection = Conn;

            try
            {
                UserXuat = "";
                if (dataGridView1.Rows.Count > 1)
                {

                    for (i = dataGridView1.Rows.Count - 2; i >= 0; i--)
                    {
                        //MaCT1 = "'Null'";

                        MaCT1 = dataGridView1.Rows[i].Cells["MaCTXuat"].Value.ToString();
                        Serial1 = dataGridView1.Rows[i].Cells["Serial"].Value.ToString();
                        SoKH1 = dataGridView1.Rows[i].Cells["SoKHXuat"].Value.ToString();
                        SoBB1 = dataGridView1.Rows[i].Cells["SoBBXuat"].Value.ToString();
                        SoXe1 = dataGridView1.Rows[i].Cells["SoXe"].Value.ToString();
                        SLXuat_d = double.Parse(dataGridView1.Rows[i].Cells["SoLuongXuat"].Value.ToString());
                        Ngay1 = dataGridView1.Rows[i].Cells["NgayInsertXuat"].Value.ToString();
                        GhiChu1 = dataGridView1.Rows[i].Cells["GhiChuoutput"].Value.ToString();
                        flag1 = dataGridView1.Rows[i].Cells["flag_out"].Value.ToString();
                        
                       
                        UserXuat = lb_user.Text;
                        cmd.Parameters.AddWithValue("@MaChiTiet", MaCT1);
                        cmd.Parameters.AddWithValue("@SoKH", SoKH1);
                        cmd.Parameters.AddWithValue("@Serial_link", Serial1);
                        cmd.Parameters.AddWithValue("@SoPhieu", SoBB1);
                        cmd.Parameters.AddWithValue("@SoXe", SoXe1);
                        cmd.Parameters.AddWithValue("@SLXP", SLXuat_d);
                        cmd.Parameters.AddWithValue("@NgayXP", Ngay1);
                        cmd.Parameters.AddWithValue("@GhiChu", GhiChu1);
                        cmd.Parameters.AddWithValue("@UserXP", UserXuat);
                        
                        //cmd.Parameters.AddWithValue("@flag", flag1);
                        cmd.Parameters.AddWithValue("@ID", SoKH1);
                      
                        cmd.Parameters.AddWithValue("@SLTheoDoi", SLXuat_d);
                        cmd.ExecuteNonQuery();
                        cmd.Parameters.Clear();
                        dataGridView1.Rows.RemoveAt(i);
                    }
                    MessageBox.Show("Dữ Liệu được lưu thành công");
                    lb_TongXuat.Text = "0";
                    dta.reset_txt(groupPanel2);
                }
                txt_Serial.Focus();



            }
            catch (Exception ex)
            {
                string s = "insert duplicate key";
                string FK = "FOREIGN KEY constraint";
                string s1 = ex.Message.ToString();
                if (s1.Contains(s))
                { MessageBox.Show("Insert không thành công \n" + "Mã đã tồn tại "); }
                else if (s1.Contains(FK))
                { MessageBox.Show("Nhập sai thông tin trong Combobox"); }
                else
                    MessageBox.Show(ex.Message);
                MessageBox.Show("Đã xảy ra lỗi khi thêm dữ liệu, vui lòng kiểm tra lại \n"+ex.Message);
            }
            finally
            {
                Conn.Close();
                cmd.Dispose();
            }
        }

        private void bt_deleteoutput_Click(object sender, EventArgs e)
        {
             DialogResult d = MessageBox.Show("Bạn có chắc muốn xóa Thông Tin " + lb_serialout.Text, "Thông Báo", MessageBoxButtons.OKCancel);
             if (d == DialogResult.OK)
             {
                 try
                 {
                     string datecheck = @"select datediff(dd,NgayInsert,getdate()) from dbo.KV2_LXP where Serial='" + lb_serialout.Text + "'";
                     //string delete = @"delete from dbo.KV1_KTG where Serial='" + lb_serialout.Text + "'";
                     Data dta = new Data();
                     SqlConnection Conn = dta.Connect();
                     Conn.Open();
                     SqlCommand cmd = new SqlCommand();
                     cmd.Connection = Conn;
                     cmd.CommandText = datecheck;
                     int date_count = int.Parse(cmd.ExecuteScalar().ToString());
                     if (date_count <= 1 || lb_user.Text == "administrator")
                     {
                         string Serial1 = lb_serialout.Text;
                         SLXuat_d = double.Parse(txt_SLoutput.Text);
                         SoKH1 = lb_SoKHoutput.Text;
          
                             cmd.CommandText = "Tran_Del_Up_XP";
                             cmd.CommandType = CommandType.StoredProcedure;
                             cmd.Parameters.AddWithValue("@Serial", Serial1);
                             cmd.Parameters.AddWithValue("@ID", SoKH1);
                             cmd.Parameters.AddWithValue("@SLTheoDoi", SLXuat_d);
                             cmd.ExecuteNonQuery();
                             MessageBox.Show("Dữ liệu được xóa thành công");
                             lb_serialout.Text = "0";
                        
                     }
                     else
                     {
                         MessageBox.Show("Quá thời gian cho phép,Không được phép xóa");
                     }
                     Conn.Close();
                     cmd.Dispose();
                     for (int i = 0; i < dataGridView4.Rows.Count - 1; i++)
                     {
                         dataGridView4.Rows.RemoveAt(0);
                     }
                     dta.reset_txt(groupPanel2);
                     bt_deleteoutput.Enabled = false;
                     bt_editoutput.Enabled = false;

                 }
                 catch (Exception ex)
                 {
                     MessageBox.Show(ex.Message);
                 }
             }
        }

        private void bt_resetoutput_Click(object sender, EventArgs e)
        {
            cb_MaSPoutput.Text = "";
            cb_MaCToutput.Text = "";
            cb_SoKHoutput.Text = "";
            txt_SoBBoutput.Text = "";
            txt_SLoutput.Text = "";
            txt_GhiChuoutput.Text = "";
            bt_insertoutput.Enabled = true;
            lb_serialout.Text = "0";
            bt_editoutput.Enabled = false;
            bt_deleteoutput.Enabled = false;
            cb_SoKHoutput.Enabled = true;
            txt_SLoutput.Enabled = true;
        }
        private void Display_output(int i)
        {
            try
            {
                MaSP1 = dataGridView4.Rows[i].Cells["MaSP"].Value.ToString();
                TenSP1 = dataGridView4.Rows[i].Cells["TenSP"].Value.ToString();
                MaCT1 = dataGridView4.Rows[i].Cells["MaCT"].Value.ToString();
                TenCT1 = dataGridView4.Rows[i].Cells["TenChiTiet"].Value.ToString();
                cb_MaSPoutput.Text = TenSP1 + " - " + MaSP1;
                cb_MaCToutput.Text = TenCT1 + " - " + MaCT1;
                txt_SoBBoutput.Text = dataGridView4.Rows[i].Cells["SoPhieu"].Value.ToString();
                cb_SoKHoutput.Text = dataGridView4.Rows[i].Cells["SoKH"].Value.ToString();
                txt_SLoutput.Text = dataGridView4.Rows[i].Cells["SLXP"].Value.ToString();
                txt_Ngayoutput.Text = dataGridView4.Rows[i].Cells["Ngay"].Value.ToString();
                lb_serialout.Text = dataGridView4.Rows[i].Cells["Serial"].Value.ToString();
                txt_Serial.Text = dataGridView4.Rows[i].Cells["Serial_link"].Value.ToString();
                txt_GhiChuoutput.Text = dataGridView4.Rows[i].Cells["GhiChu"].Value.ToString();
                txt_SoXeoutput.Text = dataGridView4.Rows[i].Cells["SoXe"].Value.ToString();
                lb_SoKHoutput.Text = dataGridView4.Rows[i].Cells["SoKH"].Value.ToString();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private void search_Output()
        {
            try
            {
                string search = null;
                Process prs = new Process();
                DataSet ds = new DataSet();
                if (cb_SoKHoutput.Text != "")
                {
                    search = @"select qry1.Serial,ChiTietSP.TenSP,ChiTietSP.MaSP,ChiTietSP.TenChiTiet,qry1.MaChiTiet as MaCT,qry1.SoPhieu,qry1.SoXe,qry1.SoKH,qry1.SLXP,qry1.Ngay,qry1.GhiChu,qry1.Serial_link from
                           (select Serial,MaChiTiet,Serial_link,SoPhieu,SoXe,SoKH,SLXP,NgayXP as Ngay,GhiChu from dbo.KV2_LXP where SoKH='" + cb_SoKHoutput.Text + "') as qry1 inner join dbo.ChiTietSP on qry1.MaChiTiet=ChiTietSP.MaChiTiet";
                }
                else
                {
                    if (cb_MaCToutput.Text != "" && txt_Ngayoutput.Text != "")
                    {
                        MaCT1 = prs.substring_right(cb_MaCToutput.Text, child);
                        string[] temp = txt_Ngayoutput.Text.Split('/');
                        Ngay1 = temp[1] + "/" + temp[0] + "/" + temp[2];
                    }
                    if (MaCT1 == "")
                        MessageBox.Show("Mã CT không chính xác");
                    else
                    {
                        search = @"select qry1.Serial,qry1.Serial_link,qry1.SoXe,ChiTietSP.TenSP,ChiTietSP.MaSP,ChiTietSP.TenChiTiet,qry1.MaChiTiet as MaCT,qry1.SoPhieu,qry1.SoKH,qry1.SLXP,qry1.Ngay,qry1.GhiChu from (select Serial,MaChiTiet,SoPhieu,SoKH,SLXP,NgayXP as Ngay,SoXe,GhiChu,Serial_link from dbo.KV2_LXP where MaChiTiet='" + MaCT1 + "' and NgayXP='" + Ngay1 + "' ) as qry1 inner join dbo.ChiTietSP on qry1.MaChiTiet=ChiTietSP.MaChiTiet";
                    }
                }
                ds = prs.dts(search);
                if (ds.Tables[0].Rows.Count == 0)
                    MessageBox.Show("Không có dữ liệu, vui lòng kiểm tra lại thông tin tìm kiếm");
                else
                {
                    dataGridView4.DataSource = ds.Tables[0];
                    int k = dataGridView4.Rows.Count - 2;
                    //lb_TonKho.Text = "1000000";
                    Display_output(k);

                    lb_indexout.Text = k.ToString();
                    bt_editoutput.Enabled = true;
                    bt_deleteoutput.Enabled = true;

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void bt_prevout_Click(object sender, EventArgs e)
        {
            try
            {
                if (dataGridView4.Rows.Count > 0)
                {
                    int i;
                    i = int.Parse(lb_indexout.Text);
                    if (i > 0)
                    {
                        i--;
                        Display_output(i);
                        lb_indexout.Text = i.ToString();
                    }
                }
            }
            catch (Exception ex)
            { MessageBox.Show(ex.Message); }
        }

        private void bt_nextout_Click(object sender, EventArgs e)
        {
            try
            {
                if (dataGridView4.Rows.Count > 0)
                {
                    int i;
                    i = int.Parse(lb_indexout.Text);
                    if (i < dataGridView4.Rows.Count - 2)
                    {
                        i++;
                        Display_output(i);
                        lb_indexout.Text = i.ToString();
                    }
                }
            }
            catch (Exception ex)
            { MessageBox.Show(ex.Message); }
        }

        private void FrKV2_XP_Load(object sender, EventArgs e)
        {
            combo_load();
        }

        private void FrKV2_XP_KeyDown(object sender, KeyEventArgs ex)
        {
            if (ex.KeyData == Keys.Enter)
            {
                SendKeys.Send("{TAB}");
            }
            if (ex.KeyData == Keys.F11)
            {
                save_output();
            }
            if (ex.KeyData == Keys.F3)
            {
                TD_LXP();
            }
            if (ex.KeyData == Keys.F7)
            {
                KV2XLR_BS();
            }
            if (ex.KeyData == Keys.F12)
            {
                if(tabControl1.SelectedTab==tab_Xuat)
                    save();
                if (tabControl1.SelectedTab == tab_chuyen)
                    buttonX4_Click(null, null);
            }
            if (ex.KeyData == Keys.F5)
            {
                KV2_XLR_TDKH();
            }
            if (ex.KeyData == Keys.End)
            {
                if(tabControl1.SelectedTab==tab_Nhap)
                    add_grid_out();
                if (tabControl1.SelectedTab == tab_Xuat)
                    add_grid();
            }
            
        }

        private void bt_saveoutput_Click(object sender, EventArgs e)
        {
            save_output();
        }

        private void dataGridView1_DoubleClick(object sender, EventArgs e)
        {
            if (dataGridView1.Rows.Count > 1)
            {
                try
                {
                    int r = dataGridView1.CurrentCell.RowIndex;
                    //MessageBox.Show(r.ToString());
                    Tong1 = double.Parse(lb_TongXuat.Text) - double.Parse(dataGridView1.Rows[r].Cells["SoLuongXuat"].Value.ToString());
                    if (Tong1 > 999)
                        lb_TongXuat.Text = string.Format("{0:###,###}", Tong1);
                    else
                        lb_TongXuat.Text = Tong1.ToString();
                    dataGridView1.Rows.RemoveAt(r);
                    //MessageBox.Show("aaaa");
                    j = dataGridView1.Rows.Count - 1;
                    dataGridView1.CurrentCell = dataGridView1.Rows[j].Cells["MaCTXuat"];
                }
                catch (Exception ex)
                { MessageBox.Show(ex.Message); }
            }
            if (dataGridView1.Rows.Count == 1)
                lb_TongXuat.Text = "0";
        }

        private void bt_searchoutput_Click(object sender, EventArgs e)
        {
            search_Output();
        }
         private DataTable dta(int n)
        {
            int j = 0;
            string colum = null;
            DataTable dt = new DataTable();
            while (j < n)
            {
                colum = j.ToString();
                dt.Columns.Add(j.ToString(), typeof(string));
                j++;
            }
            return dt;
        }
        private DataTable report(DataSet ds, int dsrows, int row_grid, int columns_grid)
         {
             i = 0;
             k = 0;
             j = 0;
             Process prs = new Process();
             SqlConnection Conn = prs.Connect();
             DataTable dt = new DataTable();
             SqlCommand cmd = new SqlCommand();
             string columnname;
             try
             {
                 Conn.Open();
                 cmd.Connection = Conn;
                 dt = dta(columns_grid);
                 int count = 0;
                 while (i < row_grid)
                 {
                     DataRow dtrow = dt.NewRow();
                     j = 0;
                     columnname = j.ToString();
                     dtrow[columnname] = ds.Tables[0].Rows[count][0].ToString();

                     j++;
                     k = count;
                     while (k < dsrows)
                     {
                         if (k < dsrows - 1)
                         {

                             if (ds.Tables[0].Rows[k][0].ToString() == ds.Tables[0].Rows[k + 1][0].ToString())
                             {
                                 for (int m = 1; m < ds.Tables[0].Columns.Count; m++)
                                 {
                                     columnname = j.ToString();
                                     dtrow[columnname] = ds.Tables[0].Rows[k][m].ToString();
                                     //MessageBox.Show(dtrow["4"].ToString());
                                     j++;
                                 }
                                 k++;
                             }
                             if (ds.Tables[0].Rows[k][0].ToString() != ds.Tables[0].Rows[k + 1][0].ToString())
                             {
                                 for (int m = 1; m < ds.Tables[0].Columns.Count; m++)
                                 {
                                     columnname = j.ToString();
                                     dtrow[columnname] = ds.Tables[0].Rows[k][m].ToString();
                                     //MessageBox.Show(dtrow["4"].ToString());
                                     j++;
                                 }

                                 //MessageBox.Show("No Khac Rui Kia");
                                 while (j < columns_grid)
                                 {
                                     //
                                     columnname = j.ToString();
                                     dtrow[columnname] = "";//chinh o day
                                     j++;
                                 }
                                 count = k + 1;
                                 dt.Rows.Add(dtrow);

                                 j = 0;
                                 break;

                             }
                         }
                         if (k == dsrows - 1)
                         {
                             if (ds.Tables[0].Rows[k][0].ToString() == ds.Tables[0].Rows[k - 1][0].ToString())
                             {
                                 for (int m = 1; m < ds.Tables[0].Columns.Count; m++)
                                 {
                                     columnname = j.ToString();
                                     dtrow[columnname] = ds.Tables[0].Rows[k][m].ToString();
                                     //MessageBox.Show(dtrow["4"].ToString());
                                     j++;
                                 }
                                 k++;
                             }
                             if (ds.Tables[0].Rows[k][0].ToString() != ds.Tables[0].Rows[k - 1][0].ToString())
                             {
                                 for (int m = 1; m < ds.Tables[0].Columns.Count; m++)
                                 {
                                     columnname = j.ToString();
                                     dtrow[columnname] = ds.Tables[0].Rows[k][m].ToString();
                                     //MessageBox.Show(dtrow["4"].ToString());
                                     j++;
                                 }

                                 //MessageBox.Show("No Khac Rui Kia");
                                 while (j < columns_grid)
                                 {
                                     //
                                     columnname = j.ToString();
                                     dtrow[columnname] = "";// chinh o day
                                     j++;
                                 }
                                 count = k + 1;
                                 dt.Rows.Add(dtrow);
                                 //MessageBox.Show(dt.Rows[0][18].ToString());
                                 j = 0;
                                 i = row_grid;
                                 break;
                             }
                         }
                     }

                     i++;
                 }
                 // MessageBox.Show(dt.Rows[20][4].ToString());
                 //dataGridView1.DataSource = dt;



             }
             catch (Exception ex)
             {
                 MessageBox.Show(ex.Message);
             }
             finally
             {
                 Conn.Close();
                 cmd.Dispose();
             }
             return dt;
         }
        private void TD_LXP()
        {
            Process prs = new Process();
            DataSet ds = new DataSet();
            DataTable dt = new DataTable();
            SqlConnection Conn = prs.Connect();
            Conn.Open();
            SqlCommand cmd = new SqlCommand();

            cmd.Connection = Conn;
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = "prc_TDKHXP";
            if (cb_MaSPReport.Text == "")
            {
                cmd.Parameters.AddWithValue("@MaSP", "test");
                cmd.Parameters.AddWithValue("@check", "0");
                ds = prs.dts_sql(cmd);
            }
            if (cb_MaSPReport.Text != "")
            {
                MaSP1 = prs.substring_right(cb_MaSPReport.Text, child);
                if (MaSP1 == "")
                    MessageBox.Show("Nhập sai thông tin SP");
                else
                {
                    cmd.Parameters.AddWithValue("@check", "1");
                    cmd.Parameters.AddWithValue("@MaSP", MaSP1);
                    ds = prs.dts_sql(cmd);
                }
            }
            ds = prs.dts_sql(cmd);
            cmd.Dispose();
            if (ds.Tables[0].Rows.Count > 0)
            {
                int count = 0;

                for (i = 0; i < ds.Tables[0].Rows.Count-1; i++)
                {
                    if (ds.Tables[0].Rows[i][0].ToString() != ds.Tables[0].Rows[i + 1][0].ToString())
                        count++;
                }
                dt = report(ds, ds.Tables[0].Rows.Count - 1, count, 100);
                //MessageBox.Show(dt.Rows.Count.ToString(), ds.Tables[0].Rows[0][0].ToString());
                if (cb_MaSPReport.Text == "")
                {
                    prs.ExportExcel(dt, "C:\\Huynh\\KV2_LXP.xls", 6, 2);
                }
                else
                    prs.ExportExcel(dt, "C:\\Huynh\\KV2_LXP_SP.xls", 6, 2);
                ds.Clear();
                dt.Clear();
            }
            Conn.Close();
            
        }
        private DataSet LXP_CLNgay(string Ngaybegin,string Ngayend,string MaSPcheck)
        {
          
            Process prs = new Process();
            DataSet ds = new DataSet();
            SqlConnection Conn = prs.Connect();
            Conn.Open();
            SqlCommand cmd = new SqlCommand();
            
            cmd.Connection = Conn;
            cmd.CommandType = CommandType.StoredProcedure;
           
          
            cmd.CommandText = "prc_LXP_CLNgay";
            cmd.Parameters.AddWithValue("@datebegin", Ngaybegin);
            cmd.Parameters.AddWithValue("@dateend", Ngayend);
            if (MaSPcheck == "0")
            {
                cmd.Parameters.AddWithValue("@MaSP", "test");
                cmd.Parameters.AddWithValue("@check", "0");
            }
            else
            {
                cmd.Parameters.AddWithValue("@MaSP", MaSPcheck);
                cmd.Parameters.AddWithValue("@check", "1");
            }
            ds = prs.dts_sql(cmd);
            cmd.Dispose();
            return ds;
           
               
        }
        private DataSet XP_Ngay(string Ngaybegin,string Ngayend,string MaSPcheck,string MaCTcheck,string Storedproceture)
        {

            Process prs = new Process();
            DataSet ds = new DataSet();
            SqlConnection Conn = prs.Connect();
            Conn.Open();
            SqlCommand cmd = new SqlCommand();

            cmd.Connection = Conn;
            cmd.CommandType = CommandType.StoredProcedure;

            cmd.CommandText = Storedproceture;
            //cmd.CommandText = "prc_XP_Ngay";
            cmd.Parameters.AddWithValue("@datebegin", Ngaybegin);
            cmd.Parameters.AddWithValue("@dateend", Ngayend);
           // cmd.Parameters.AddWithValue("@dateend", Ngayend);
            if (MaSPcheck == "0")
            {
                cmd.Parameters.AddWithValue("@MaSP", "test");
                cmd.Parameters.AddWithValue("@check", "0");
                cmd.Parameters.AddWithValue("@MaChiTiet", "test");
            }
            else
            {
                if (MaCTcheck == "0")
                {
                    cmd.Parameters.AddWithValue("@MaSP", MaSPcheck);
                    cmd.Parameters.AddWithValue("@MaChiTiet", "test");
                    cmd.Parameters.AddWithValue("@check", "1");
                }
                else
                {

                    cmd.Parameters.AddWithValue("@MaSP", MaSPcheck);
                    cmd.Parameters.AddWithValue("@MaChiTiet", MaCTcheck);
                    cmd.Parameters.AddWithValue("@check", "2");
                }
            }
            ds = prs.dts_sql(cmd);
            cmd.Dispose();
            Conn.Close();
            return ds;


        }
        private void bt_printreport_Click(object sender, EventArgs e)
        {
            Process prs=new Process();
            try
            {
                string[] temp = txt_NgayStart.Text.Split('/');
                Ngay_start1 = temp[1] + "/" + temp[0] + "/" + temp[2] + " 00:00:00";
                string[] temp2 = txt_Ngayend.Text.Split('/');
                Ngay_End1 = temp2[1] + "/" + temp2[0] + "/" + temp2[2] + " 23:59:59";
                DataSet ds = new DataSet();
                if (cb_MaSPReport.Text != "")
                {

                    MaSP1 = prs.substring_right(cb_MaSPReport.Text, child);
                    if (MaSP1 == "")
                        MessageBox.Show("Nhập sai thông tin SP");
                    else
                    {
                        ds = LXP_CLNgay(Ngay_start1, Ngay_End1, MaSP1);
                    }
                }
                else
                    ds = LXP_CLNgay(Ngay_start1, Ngay_End1, "0");
                Fr_Report FrR = new Fr_Report();
                Ngay_start1 = txt_NgayStart.Text;
                Ngay_End1 = " - " + txt_Ngayend.Text;
                FrR.report_KV2XP_CL(ds, Ngay_start1, Ngay_End1);
                FrR.Show();
                ds.Clear();
                temp.Clone();
                temp2.Clone();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void bt_printXuat_Click(object sender, EventArgs e)
        {
            Process prs = new Process();
            try
            {
                DataSet ds = new DataSet();
                string[] temp = txt_Ngayoutput.Text.Split('/');
                Ngay_start1 = temp[1] + "/" + temp[0] + "/" + temp[2] + " " + maskedTextBox1.Text;
                Ngay_End1 = temp[1] + "/" + temp[0] + "/" + temp[2] + " " + maskedTextBox2.Text;
                //MessageBox.Show(Ngay_start1 + " " + Ngay_End1);
                if (cb_MaSPoutput.Text != "")
                {
                    MaSP1 = prs.substring_right(cb_MaSPoutput.Text, child);
                    if (MaSP1 == "")
                        MessageBox.Show("Nhập sai Mã SP");
                    else
                    {
                        if (cb_MaCToutput.Text == "")
                            ds = XP_Ngay(Ngay_start1,Ngay_End1, MaSP1, "0", "prc_XP_NgayGio");
                        else
                        {
                            MaCT1 = prs.substring_right(cb_MaCToutput.Text, child);
                            ds = XP_Ngay(Ngay_start1,Ngay_End1, MaSP1, MaCT1, "prc_XP_NgayGio");
                        }


                    }
                }
                else
                    ds = XP_Ngay(Ngay_start1,Ngay_End1, "0", "0", "prc_XP_NgayGio");
                Fr_Report FrR = new Fr_Report();
                Ngay_start1 = txt_Ngayoutput.Text;
                
                FrR.report_KV2XP_Ngay(ds, Ngay_start1);
                FrR.Show();
                ds.Clear();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        public void Users(string Users)
        {
            lb_user.Text = Users;
        }

        private void lb_user_TextChanged(object sender, EventArgs e)
        {
            Check_User();
        }
        private void KV2_KTam()
        {
            Process prs = new Process();
            DataSet ds = new DataSet();
            SqlConnection Conn = prs.Connect();
            Conn.Open();
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = Conn;
            cmd.CommandType = CommandType.StoredProcedure;
            try
            {
                string[] temp = txt_NgayStart.Text.Split('/');
                Ngay_start1 = temp[1] + "/" + temp[0] + "/" + temp[2] + " 00:00:00";
                string[] temp2 = txt_Ngayend.Text.Split('/');
                Ngay_End1 = temp2[1] + "/" + temp2[0] + "/" + temp2[2] + " 23:59:59";
                cmd.CommandText = "prc_KV2_KTam";
                cmd.Parameters.AddWithValue("@datebegin", Ngay_start1);
                cmd.Parameters.AddWithValue("@dateend", Ngay_End1);
                //MessageBox.Show(Ngay_start1 + " " + Ngay_End1);
                ds = prs.dts_sql(cmd);
                Ngay_start1 = txt_NgayStart.Text;
                Ngay_End1 = " - " + txt_Ngayend.Text;
                Fr_Report FrR = new Fr_Report();
                FrR.report_KV2_KTam(ds, Ngay_start1, Ngay_End1);
                FrR.Show();
                ds.Clear();
                temp.Clone();
                temp2.Clone();
                
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                Conn.Close();
                cmd.Dispose();
            }

            

        }

        private void bt_excelreport_Click(object sender, EventArgs e)
        {
            string[] temp = txt_NgayStart.Text.Split('/');
            Ngay_start1 = temp[1] + "/" + temp[0] + "/" + temp[2] + " 00:00:00";
            string[] temp2 = txt_Ngayend.Text.Split('/');
            Ngay_End1 = temp2[1] + "/" + temp2[0] + "/" + temp2[2] + " 23:59:59";
            string temp_string = @"SELECT     dbo.KV1_KTG.MaCT,dbo.Load_CTSP_Mua.TenSP,dbo.Load_CTSP_Mua.TenChiTiet,dbo.KV1_KTG.Serial,  dbo.KV1_KTG.SoBB, dbo.KV1_KTG.SoXe, left(dbo.KV1_KTG.SoKH,5) as SoKH, dbo.KV1_KTG.SLXuat, dbo.KV1_KTG.Ngay, 
                      dbo.KV2_LXP.SLXP, dbo.KV2_LXP.NgayXP
                        FROM         dbo.KV1_KTG INNER JOIN
                      dbo.KV2_LXP ON dbo.KV1_KTG.Serial = dbo.KV2_LXP.Serial_link and NgayXP>='" + Ngay_start1 + "' and NgayXP<='" + Ngay_End1 + "' inner join dbo.Load_CTSP_Mua on dbo.Load_CTSP_Mua.MaChiTiet=KV1_KTG.MaCT ";
            Process prs = new Process();
            DataSet ds = new DataSet();
            try
            {
                ds = prs.dts(temp_string);
                prs.ExportExcel(ds.Tables[0],"C:\\Huynh\\KV2_Data.xlsx",6,1);
                ds.Clear();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void bt_searchKH_Click(object sender, EventArgs e)
        {
            Process prs = new Process();
            DataSet ds = new DataSet();
            try
            {
                GhiChu1 = @"SELECT 
                              Load_CTSP_Mua.TenSP,Load_CTSP_Mua.TenChiTiet
                              ,left([ID_KeHoach],5) as MaKH
                              ,[SLKH] as SoLuong
                              ,SLKH-SLTheoDoi as SLXuat
                              ,[SLTheoDoi] as SLTon
                              ,[Ngay] as NgayXP
                          FROM [dbo].[KH_Theodoi]
                          inner join dbo.Load_CTSP_Mua on dbo.Load_CTSP_Mua.MaChiTiet=KH_Theodoi.MaCT
                          where ID_KeHoach like '%KV2XP%'";
                if (txt_TDKeHoach.Text != "")
                    GhiChu1 += " and ID_KeHoach like '%" + txt_TDKeHoach.Text + "%'";
                if (cb_MaSPKH.Text != "")
                    GhiChu1 += " and MaCT like '%" + prs.substring_right(cb_MaSPKH.Text, child) + "%'";
                GhiChu1 += " order by ID_KeHoach";
                ds = prs.dts(GhiChu1);
                GhiChu1 = "KẾ HOẠCH XUỐNG PHIẾU";
                
                Fr_Report FrR = new Fr_Report();

                FrR.report_KHKV2XP(ds, GhiChu1);
                FrR.Show();
                ds.Clear();

                    
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
            }
        }
        private void add_grid()
        {
            SqlCommand cmd = new SqlCommand();
            SqlConnection Conn = new SqlConnection();
            Process prs = new Process();
            Conn = prs.Connect();
            Conn.Open();
            cmd.Connection = Conn;
            try
            {

                TenSP1 = prs.substring_left(cb_MaSP.Text, child);
                TenCT1 = prs.substring_left(cb_MaCT.Text, child);
                MaCT1 = prs.substring_right(cb_MaCT.Text, child);
                if (TenSP1 == "" || MaCT1 == "" || txt_Ngay.Text == "" || txt_SLXuat.Text == "" || txt_SoPhieu.Text == "" || cb_LyDoXuat.Text == "")
                {
                    MessageBox.Show("Thông Tin Nhập Không Chính Xác Hoặc Thiếu");
                }
                else
                {

                    LyDo1 = cb_LyDoXuat.Text;
                    Ngay1 = txt_Ngay.Text.Trim();
                    SLXuat_d = double.Parse(txt_SLXuat.Text);
                    SoPhieu1 = txt_SoPhieu.Text;
                    SoXe1 = txt_SoXe.Text;
                    GhiChu1 = txt_GhiChu.Text;
                    string[] temp = Ngay1.Split('/');
                    NgayInsert1 = temp[1] + "/" + temp[0] + "/" + temp[2];
                    i = 0;
                    #region //Kiểm tra grid
                    if (rd_ChiTiet.Checked == true)
                    {
                        if (dataGridView3.Rows.Count > 1)
                        {
                            while (i < dataGridView3.Rows.Count - 1)
                            {
                                if (MaCT1 != dataGridView3.Rows[i].Cells["MaCT"].Value.ToString())
                                    i++;
                                else
                                    break;
                            }
                        }
                        if (dataGridView3.Rows.Count == 1 || i == dataGridView3.Rows.Count - 1)
                        {
                            #region //kiểm tra dữ liệu nhập
                            k = cb_MaCT.Items.Count - 1;
                            while (k >= 0)
                            {

                                if (MaCT1 == prs.substring_right(cb_MaCT.Items[k].ToString(), child))
                                    break;
                                else
                                    k--;
                            }


                            if (k >= 0)
                            {
                                for (i = 0; i < cb_SoPhieuAdd.Items.Count; i++)
                                {
                                    if (txt_SoPhieu.Text == cb_SoPhieuAdd.Items[i].ToString())
                                        break;
                                }
                                if (i < cb_SoPhieuAdd.Items.Count)
                                {
                                    if (SoPhieu1.Length < 5)
                                    {
                                        if (SoPhieu1.Length == 1)
                                            SoPhieu1 = "0000" + SoPhieu1;
                                        if (SoPhieu1.Length == 2)
                                            SoPhieu1 = "000" + SoPhieu1;
                                        if (SoPhieu1.Length == 3)
                                            SoPhieu1 = "00" + SoPhieu1;
                                        if (SoPhieu1.Length == 4)
                                            SoPhieu1 = "0" + SoPhieu1;
                                    }

                                    dataGridView3.Rows.Add(TenSP1, MaCT1, TenCT1, "BS" + SoPhieu1 + MaCT1, LyDo1, SLXuat_d, Ngay1, NgayInsert1, SoXe1, GhiChu1, "0");
                                    txt_SLXuat.Text = "";
                                    cb_MaCT.Text = "";
                                    txt_GhiChu.Text = "";
                                    txt_SoXe.Text = "";
                                    Tong1 = double.Parse(lb_Tong.Text);
                                    Tong1 += SLXuat_d;
                                    //lb_TongXuat.Text = Tong1.ToString();
                                    lb_Tong.Text = string.Format("{0:###,###}", Tong1);
                                    txt_SoPhieu.Enabled = true;
                                    cb_MaSP.Focus();
                                    prs.formatcolordatagrid(dataGridView3);
                                }
                                else
                                    MessageBox.Show("Bạn đang nhập một số phiếu không đúng");
                            }
                            #endregion
                            else
                                MessageBox.Show("Kiểm tra lại Mã CT hoặc Số KH");
                        }

                    #endregion
                        else
                            MessageBox.Show("Chi tiết này đã có trong DS phía dưới. Bạn cần lưu DS này trước");
                    }
                    if (rd_Ve.Checked == true)
                    {
                        if (dataGridView3.Rows.Count > 1)
                            MessageBox.Show("Bạn cần lưu danh sách phía dưới trước");
                        else
                        {
                            SoPhieu1 = txt_SoPhieu.Text;
                            if (SoPhieu1.Length < 5)
                            {
                                if (SoPhieu1.Length == 1)
                                    SoPhieu1 = "0000" + SoPhieu1;
                                if (SoPhieu1.Length == 2)
                                    SoPhieu1 = "000" + SoPhieu1;
                                if (SoPhieu1.Length == 3)
                                    SoPhieu1 = "00" + SoPhieu1;
                                if (SoPhieu1.Length == 4)
                                    SoPhieu1 = "0" + SoPhieu1;
                            }
                            cmd.CommandText = "select datepart(yyyy,getdate())";
                            lb_SLKH.Text = SoPhieu1 + "KV2XLR" + cmd.ExecuteScalar().ToString();
                            SoPhieu1 = lb_SLKH.Text;
                            for (i = 0; i < dataGridView2.Rows.Count - 1; i++)
                            {
                                if (MaCT1 == dataGridView2.Rows[i].Cells["ID_link"].Value.ToString())
                                {
                                    string_temp = dataGridView2.Rows[i].Cells["MaCT"].Value.ToString();
                                    MaSP1 = dataGridView2.Rows[i].Cells["MaSP"].Value.ToString();
                                    TenSP1 = dataGridView2.Rows[i].Cells["TenSP"].Value.ToString();
                                    TenCT1 = dataGridView2.Rows[i].Cells["TenChiTiet"].Value.ToString();
                                    SLtemp_d = SLXuat_d * double.Parse(dataGridView2.Rows[i].Cells["SLCT_QuyDoi"].Value.ToString());
                                    dataGridView3.Rows.Add(TenSP1, string_temp, TenCT1, SoPhieu1, LyDo1, SLtemp_d, Ngay1, NgayInsert1, SoXe1, GhiChu1, "0");
                                    Tong1 = double.Parse(lb_Tong.Text);
                                    Tong1 += SLtemp_d;
                                }
                            }
                            txt_SLXuat.Enabled = false;
                            txt_SoPhieu.Enabled = false;
                            cb_MaCT.Enabled = false;
                            cb_MaSP.Enabled = false;
                            lb_Tong.Text = string.Format("{0:###,###}", Tong1);
                        }
                    }
                    j = dataGridView3.Rows.Count - 1;
                    dataGridView3.CurrentCell = dataGridView3.Rows[j].Cells[0];
                    dataGridView3.FirstDisplayedCell = dataGridView3.Rows[j].Cells[0];
                    prs.formatcolordatagrid(dataGridView3);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                Conn.Close();
                cmd.Dispose();
            }
        }
        private void bt_insert_Click(object sender, EventArgs e)
        {
            add_grid();
        }

        private void cb_MaSP_SelectedIndexChanged(object sender, EventArgs e)
        {
            Process prs = new Process();

            MaSP1 = prs.substring_right(cb_MaSP.Text, child);
            cb_MaCT.Items.Clear();

            cb_MaCT.Text = "";
            for (i = dataGridView_LoadSP.Rows.Count - 2; i >= 0; i--)
            {
                if (MaSP1 == dataGridView_LoadSP.Rows[i].Cells[0].Value.ToString())
                {
                    cb_MaCT.Items.Add(dataGridView_LoadSP.Rows[i].Cells[1].Value.ToString());
                }
            }

        }

        private void cb_MaCT_SelectedIndexChanged(object sender, EventArgs e)
        {
            Process prs = new Process();
            //FormProcess Frp = new FormProcess();
            SqlConnection Conn = prs.Connect();
            SqlCommand cmd = new SqlCommand();

            try
            {
                Conn.Open();
                cmd.Connection = Conn;
                MaCT1 = prs.substring_right(cb_MaCT.Text, child);
                if (rd_Ve.Checked == true)
                {
                    string_temp = @"select min(floor(dbo.KV2_TK.SLTon/SLCT_QuyDoi)) as TonKho from dbo.KV2_TK where ID_link='" + MaCT1 + "'";
                }
                if (rd_ChiTiet.Checked == true)
                {
                    string_temp = @"select dbo.KV2_TK.SLTon from dbo.KV2_TK where MaCT='"+MaCT1+"'";
                }
                cmd.CommandText = string_temp;
                lb_SLTon.Text = cmd.ExecuteScalar().ToString();
                //GhiChu1 = @"select left(ID_KeHoach,5),ID from KH_TheoDoi where SLTheoDoi>0 and MaCT='" + MaCT1 + "' and ID_KeHoach like '%KV2XLR%'";
               // Frp.cb1(cb_LyDoXuat, GhiChu1, 0, 1);
                
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                lb_SLTon.Text = "0";

            }
            finally
            {
                Conn.Close();
                cmd.Dispose();
            }
        }

       /* private void cb_SoKH_Leave(object sender, EventArgs e)
        {
            FormProcess Frp = new FormProcess();
            Process prs = new Process();
            SqlConnection Conn = prs.Connect();
            Conn.Open();
            SqlCommand cmd = new SqlCommand();
            try
            {
                SoKH1 = prs.substring_right(cb_LyDoXuat.Text, child);
                string check_SL = null;
                check_SL = @"select SLTheoDoi from dbo.KH_TheoDoi where ID='" + SoKH1 + "'";
                cmd.CommandText = check_SL;
                cmd.Connection = Conn;
                lb_SLKH.Text = cmd.ExecuteScalar().ToString();
            }
            catch
            {
                //MessageBox.Show(ex.Message);
                cb_LyDoXuat.Text = "";
                txt_SLXuat.Text = "0";
            }
            finally
            {
                Conn.Close();
                cmd.Dispose();
            }
        }*/

        private void txt_SLXuat_Leave(object sender, EventArgs e)
        {
            try
            {
                Tong1 = double.Parse(lb_SLTon.Text);
                if (txt_SLXuat.Text != "")
                {
                    SLXuat_d = double.Parse(txt_SLXuat.Text);
                    if (SLXuat_d> Tong1)
                    {
                        MessageBox.Show("Số lượng xuất không vượt quá số lượng tồn kho");
                        txt_SLXuat.Text = "";
                        //txt_SLinput.Focus();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void bt_edit_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Phần mềm không hỗ trợ chức năng này, bạn có thể  xóa dữ liệu sai, sau đó thêm mới");
        }
        private void save()
        {
            
            Process prs = new Process();
            SqlConnection Conn = prs.Connect();
          
            SqlCommand cmd = new SqlCommand();
            Conn.Open();
            cmd.Connection = Conn;
            int count = 0;
            try
            {
               
                UserXuat = "";
                MaCT1 = prs.substring_right(cb_MaCT.Text, child);
                if (dataGridView3.Rows.Count > 1)
                {
                    if(MaCT1!=""&&lb_SLKH.Text != "")
                    {
                        MaSP1 = prs.substring_right(cb_MaSP.Text, child);
                        SLXuat_d = double.Parse(txt_SLXuat.Text);
                        string_temp = @"INSERT INTO [dbo].[KeHoachSP]([ID],[MaKeHoach],[TenKeHoach],[MaSP],[SoLuongSP],[KhuVuc])
                        VALUES(N'" + lb_SLKH.Text + "',N'" + txt_SoPhieu.Text + "',N'KV2XLR',N'" + MaSP1 + "'," + SLXuat_d + ",N'KV2XLR')";
                        cmd.CommandText = string_temp;
                        cmd.ExecuteNonQuery();
                        count = 1;
                        cmd.CommandText = @"insert into dbo.KH_TheoDoi(ID,MaCT,ID_KeHoach,SLKH,SLTheoDoi,Ngay)
                                  Values('"+lb_SLKH.Text+MaCT1+"',N'"+MaCT1+"','"+lb_SLKH.Text+"',"+SLXuat_d+","+SLXuat_d+",getdate())";
                        cmd.ExecuteNonQuery();
                        count = 2;
                    }
                   // MessageBox.Show("aaaa");
                    cmd.CommandText = "Tran_Ins_Up_XLR";
                    cmd.CommandType = CommandType.StoredProcedure;
                    for (i = dataGridView3.Rows.Count - 2; i >= 0; i--)
                    {
                        MaCT1 = dataGridView3.Rows[i].Cells["MaCT"].Value.ToString();
                        
                        SoPhieu1 = dataGridView3.Rows[i].Cells["SoPhieu"].Value.ToString();
                        SoXe1 = dataGridView3.Rows[i].Cells["SoXeXuat"].Value.ToString();
                      
                        SLXuat_d = double.Parse(dataGridView3.Rows[i].Cells["SLXuat"].Value.ToString());
                        LyDo1 = dataGridView3.Rows[i].Cells["LyDoXuat"].Value.ToString();
                        Ngay1 = dataGridView3.Rows[i].Cells["NgayInsert"].Value.ToString();
                        GhiChu1 = dataGridView3.Rows[i].Cells["GhiChu"].Value.ToString();

                        UserXuat = lb_user.Text;
                        cmd.Parameters.AddWithValue("@MaChiTiet", MaCT1);
                        cmd.Parameters.AddWithValue("@SoPhieu", SoPhieu1);
                        cmd.Parameters.AddWithValue("@SoXe", SoXe1);
                        cmd.Parameters.AddWithValue("@SLXLR", SLXuat_d);
                        cmd.Parameters.AddWithValue("@LyDoXuat", LyDo1);
                        cmd.Parameters.AddWithValue("@Ngay", Ngay1);
                        cmd.Parameters.AddWithValue("@GhiChu", GhiChu1);
                        cmd.Parameters.AddWithValue("@UserXLR", UserXuat);
                        cmd.ExecuteNonQuery();
                        cmd.Parameters.Clear();
                        dataGridView3.Rows.RemoveAt(i);
                    }
                   
                    lb_Tong.Text = "0";
                    MessageBox.Show("Dữ Liệu được lưu thành công");
                    txt_SoPhieu.Enabled = true;
                    txt_SLXuat.Enabled = true;
                    cb_MaCT.Enabled = true;
                    txt_PhieuPallet.Text = SoPhieu1;
                    lb_SLKH.Text = "";
                    cb_MaSP.Enabled = true;
                    cb_MaSP.Text = "";
                    txt_SoPhieu.Text = "";
                    txt_SoXe.Text = "";
                    txt_SLXuat.Text = "";
                  
                   
                    count = 3;
                }



            }
            catch (Exception ex)
            {
                string s = "insert duplicate key";
                string FK = "FOREIGN KEY constraint";
                string s1 = ex.Message.ToString();
                if (s1.Contains(s))
                { MessageBox.Show("Insert không thành công \n" + "Mã đã tồn tại "); }
                else if (s1.Contains(FK))
                { MessageBox.Show("Nhập sai thông tin trong Combobox");
                MessageBox.Show(ex.Message);
                }
                else
                    MessageBox.Show(ex.Message);
                MessageBox.Show("Đã xảy ra lỗi khi thêm dữ liệu, vui lòng kiểm tra lại");
                if (count>0 && count<3)
                {
                    SqlCommand cmd1 = new SqlCommand();
                    cmd1.Connection = Conn;
                    cmd1.CommandText = @"delete from dbo.KeHoachSP where ID='" + lb_SLKH.Text + "'";
                    cmd1.ExecuteNonQuery();
                    cmd1.CommandText = @"delete from dbo.KV2_XLR where SoPhieu='" + txt_SoPhieu.Text + "'";
                    cmd1.ExecuteNonQuery();
                    cmd1.Dispose();
                }
            }
            finally
            {
                Conn.Close();
                cmd.Dispose();
            }
        }
        
        private void bt_save_Click(object sender, EventArgs e)
        {
            save();
        }

        private void rd_Ve_CheckedChanged(object sender, EventArgs e)
        {
            lb_SLTon.Text = "0";

        }

        private void bt_reset_Click(object sender, EventArgs e)
        {
            cb_MaCT.Text = "";
            cb_MaCT.Enabled = true;
            cb_MaSP.Text = "";
            txt_SLXuat.Text = "";
            txt_SLXuat.Enabled = true;
            txt_SoPhieu.Text = "";
            txt_SoPhieu.Enabled = true;
            cb_MaSP.Enabled = true;
            txt_GhiChu.Text = "";
            txt_SoXe.Text = "";
            lb_SLKH.Text = "";
            lb_Tong.Text = "0";
            txt_SoPhieu.Enabled = true;
            dataGridView3.Rows.Clear();
            bt_edit.Enabled = false;
            bt_delete.Enabled = false;
        }

        private void dataGridView3_DoubleClick(object sender, EventArgs e)
        {
            if (dataGridView3.Rows.Count > 1)
            {
                try
                {
                    if (lb_SLKH.Text == "")
                    {
                        int r = dataGridView3.CurrentCell.RowIndex;
                        //MessageBox.Show(r.ToString());
                        Tong1 = double.Parse(lb_Tong.Text) - double.Parse(dataGridView3.Rows[r].Cells["SLXuat"].Value.ToString());
                        if (Tong1 > 999)
                            lb_Tong.Text = string.Format("{0:###,###}", Tong1);
                        else
                            lb_Tong.Text = Tong1.ToString();
                        dataGridView3.Rows.RemoveAt(r);
                        //MessageBox.Show("aaaa");
                        j = dataGridView3.Rows.Count - 1;
                        dataGridView3.CurrentCell = dataGridView3.Rows[j].Cells["MaCT"];
                        //lb_SLKH.Text = "";
                    }
                    else
                        MessageBox.Show("Chi tiết này không thể xóa, do tính chất đồng bộ của Vế");
                }
                catch (Exception ex)
                { MessageBox.Show(ex.Message); }
            }
        }
        private void Search_XLR()
        {
            try
            {
                Process prs = new Process();
                string_temp = @"SELECT 
                    Load_CTSP_Mua.TenSP+' - '+Load_CTSP_Mua.MaSP as MaSP,
                      TenChiTiet+' - '+Load_CTSP_Mua.MaChiTiet  as MaCT
                      ,[SoPhieu]
                      ,[SoXe]
                      ,[SLXLR],LyDoXuat
                      ,[Ngay]
                      ,[GhiChu]
                        from dbo.KV2_XLR inner join dbo.Load_CTSP_Mua on Load_CTSP_Mua.MaChiTiet=KV2_XLR.MaChiTiet and SoPhieu like '%" + txt_SoPhieu.Text + "%'";
                DataSet ds = new DataSet();
                ds = prs.dts(string_temp);

                if (ds.Tables[0].Rows.Count == 0)
                    MessageBox.Show("Không có dữ liệu, vui lòng kiểm tra lại thông tin tìm kiếm");
                else
                {
                    dataGridView5.DataSource = ds.Tables[0];
                    i = dataGridView5.Rows.Count - 2;
                    lb_indexXuat.Text = i.ToString();
                    Display_XLR(i);
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            
        }
        private void Display_XLR(int k)
        {
            cb_MaSP.Text = dataGridView5.Rows[k].Cells["MaSP"].Value.ToString();
            cb_MaCT.Text = dataGridView5.Rows[k].Cells["MaCT"].Value.ToString();
            cb_LyDoXuat.Text = dataGridView5.Rows[k].Cells["LyDoXuat"].Value.ToString();
            txt_SLXuat.Text = dataGridView5.Rows[k].Cells["SLXLR"].Value.ToString();
            txt_SoPhieu.Text = dataGridView5.Rows[k].Cells["SoPhieu"].Value.ToString();
            txt_SoXe.Text = dataGridView5.Rows[k].Cells["SoXe"].Value.ToString();
            txt_GhiChu.Text = dataGridView5.Rows[k].Cells["GhiChu"].Value.ToString();
            txt_Ngay.Text = dataGridView5.Rows[k].Cells["Ngay"].Value.ToString();
            txt_SoPhieu.Enabled = false;
        }

        private void bt_search_Click(object sender, EventArgs e)
        {
            Search_XLR();
            bt_delete.Enabled = true;
            bt_edit.Enabled = true;
        }

        private void bt_prev_Click(object sender, EventArgs e)
        {
            try
            {
                if (dataGridView5.Rows.Count > 0)
                {
                    int i;
                    i = int.Parse(lb_indexXuat.Text);
                    if (i > 0)
                    {
                        i--;
                        Display_XLR(i);
                        lb_indexXuat.Text = i.ToString();
                    }
                }
            }
            catch (Exception ex)
            { MessageBox.Show(ex.Message); }
        }

        private void bt_next_Click(object sender, EventArgs e)
        {
            try
            {
                if (dataGridView5.Rows.Count > 0)
                {
                    int i;
                    i = int.Parse(lb_indexXuat.Text);
                    if (i < dataGridView5.Rows.Count - 2)
                    {
                        i++;
                        Display_XLR(i);
                        lb_indexXuat.Text = i.ToString();
                    }
                }
            }
            catch (Exception ex)
            { MessageBox.Show(ex.Message); }
        }
        private void delete_XLR()
        {
            DialogResult d = MessageBox.Show("Tất cả những thông tin có Số Phiếu này đều bị xóa. Bạn có chắc muốn xóa " +txt_SoPhieu.Text, "Thông Báo", MessageBoxButtons.OKCancel);
            if (d == DialogResult.OK)
            {
                try
                {
                    string datecheck = @"select min(datediff(dd,NgayInsert,getdate())) from dbo.KV2_XLR where SoPhieu='" + txt_SoPhieu.Text + "'";
                    //string delete = @"delete from dbo.KV1_KTG where Serial='" + lb_serialout.Text + "'";
                    Data dta = new Data();
                    SqlConnection Conn = dta.Connect();
                    Conn.Open();
                    SqlCommand cmd = new SqlCommand();
                    cmd.Connection = Conn;
                    cmd.CommandText = datecheck;
                    SoPhieu1 = txt_SoPhieu.Text;
                    int date_count = int.Parse(cmd.ExecuteScalar().ToString());
                    if (date_count <= 1||lb_user.Text=="administrator")
                    {
                        //SqlDataReader rd = new SqlDataReader;
                        cmd.CommandText = "SELECT [SoBB] FROM [DataBase_ScansiaPacific2013].[dbo].[KV4_KTam] where SoBB like '"+txt_SoPhieu.Text+"%'";
                        SqlDataReader rd = cmd.ExecuteReader();
                        if (rd.Read() == false)
                        {
                            rd.Close();
                            cmd.CommandText = "Tran_Del_Up_XLR";
                            cmd.CommandType = CommandType.StoredProcedure;
                            cmd.Parameters.AddWithValue("@SoPhieu", SoPhieu1);
                            cmd.ExecuteNonQuery();
                            MessageBox.Show("Dữ liệu được xóa thành công");
                        }
                        else
                        {
                            MessageBox.Show("Số phiếu này đã phát sinh tại Kho Tạm, nếu muốn xóa, bạn cần liên hệ với NV Kho Tạm, hoặc Quản Trị Viên");
                            MessageBox.Show("DỮ LIỆU XÓA KHÔNG THÀNH CÔNG");
                        }
                       /* */

                    }
                    else
                    {
                        MessageBox.Show("Quá thời gian cho phép,Không được phép xóa");
                    }
                    Conn.Close();
                    cmd.Dispose();
                    for (int i = 0; i < dataGridView5.Rows.Count - 1; i++)
                    {
                        dataGridView5.Rows.RemoveAt(0);
                    }
                    bt_reset_Click(null, null);
                    bt_delete.Enabled = false;
                    bt_edit.Enabled = false;

                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }

        private void bt_delete_Click(object sender, EventArgs e)
        {
            delete_XLR();
        }
        private void Print_PhieuXuat()
        {
            DataSet ds = new DataSet();
            Process prs = new Process();
            try
            {
                string_temp = @"
                            select qry1.TenSP,qry1.MaSP,qry1.LoaiGo,qry1.TenChiTiet,dbo.Load_CTSP_Mua.TenChiTiet as TenNCC,qry1.MaChiTiet,qry1.LyDoXuat as LyDoNhap,convert(nvarchar(10),qry1.Ngay,103) as NgayNhap,qry1.SLXuat/qry1.SLCT_QuyDoi as SoLuong,qry1.SoPhieu,qry1.SLXuat,qry1.SoLuongCT  from
                            (select dbo.Load_CTSP_Mua.TenSP,ChiTiet_KhuVuc.SLCT_QuyDoi as SoLuongCT,dbo.Load_CTSP_Mua.MaSP,dbo.Load_CTSP_Mua.TenChiTiet,dbo.Load_CTSP_Mua.LoaiGo,ChiTiet_KhuVuc.ID_link,ChiTiet_KhuVuc.SLCT_QuyDoi,ChiTiet_KhuVuc.MaCT as MaChiTiet,KV2_XLR.SLXLR as SLXuat,KV2_XLR.LyDoXuat,KV2_XLR.SoPhieu,KV2_XLR.Ngay
                            from dbo.KV2_XLR inner join ChiTiet_KhuVuc on ChiTiet_KhuVuc.MaCT=dbo.KV2_XLR.MaChiTiet and ChiTiet_KhuVuc.KhuVuc='KV2XLR' and SoPhieu='" + txt_PhieuPallet.Text + "' inner join dbo.Load_CTSP_Mua on dbo.Load_CTSP_Mua.MaChiTiet=KV2_XLR.MaChiTiet) as qry1 inner join dbo.Load_CTSP_Mua on dbo.Load_CTSP_Mua.MaChiTiet=qry1.ID_link";
                Fr_Report FrR = new Fr_Report();

                ds = prs.dts(string_temp);
                FrR.report_KV2XLR(ds);
                FrR.Show();
                ds.Clear();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void txt_PhieuPallet_Leave(object sender, EventArgs e)
        {
            Print_PhieuXuat();
        }
        private void lik_PhieuPallet_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            txt_PhieuPallet.Visible = true;
        }
        private void bt_print_Click(object sender, EventArgs e)
        {
            Process prs = new Process();
            try
            {
                DataSet ds = new DataSet();
                string[] temp = txt_Ngay.Text.Split('/');
                Ngay_start1 = temp[1] + "/" + temp[0] + "/" + temp[2]+" 00:00:00";
                Ngay_End1 = temp[1] + "/" + temp[0] + "/" + temp[2] + " 23:59:59";

                if (cb_MaSP.Text != "")
                {
                    MaSP1 = prs.substring_right(cb_MaSP.Text, child);
                    if (MaSP1 == "")
                        MessageBox.Show("Nhập sai Mã SP");
                    else
                    {
                        if (cb_MaCT.Text == "")
                            ds = XP_Ngay(Ngay_start1,Ngay_End1, MaSP1, "0", "prc_XLR_Ngay");
                        else
                        {
                            MaCT1 = prs.substring_right(cb_MaCT.Text, child); 
                            ds = XP_Ngay(Ngay_start1,Ngay_End1, MaSP1, MaCT1, "prc_XLR_Ngay");
                        }
                    }
                }
                else
                    ds = XP_Ngay(Ngay_start1,Ngay_End1, "0", "0", "prc_XLR_Ngay");
                Fr_Report FrR = new Fr_Report();
                Ngay_start1 = txt_Ngay.Text;
                FrR.report_KV2XLR_Ngay(ds, Ngay_start1);
                FrR.Show();
                ds.Clear();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
       
        private void TonKho_Tab()
        {
           
            try
            {
                DataSet ds=new DataSet();
                Process prs = new Process();
                string_temp = @"select dbo.Load_CTSP_Mua.TenSP,qry1.MaCT,qry1.TenChiTiet1,qry1.SLCT_QuyDoi,qry1.SLTon,qry1.ID_link,dbo.Load_CTSP_Mua.TenChiTiet,floor(qry1.SLTon/qry1.SLCT_QuyDoi) as DBTon from
                                (SELECT [MaCT],dbo.Load_CTSP_Mua.TenChiTiet as TenChiTiet1,[SLCT_QuyDoi],[SLTon],[ID_link]
                                FROM [dbo].[KV2_TK] inner join dbo.Load_CTSP_Mua on dbo.Load_CTSP_Mua.MaChiTiet=[dbo].[KV2_TK].MaCT) as qry1
                                inner join dbo.Load_CTSP_Mua on dbo.Load_CTSP_Mua.MaChiTiet=qry1.ID_Link";
               
                if (cb_MaSPTK.Text != "")
                {
                    MaSP1 = prs.substring_right(cb_MaSPTK.Text, child);
                    if (MaSP1 != "")
                    {
                        string_temp += " and dbo.Load_CTSP_Mua.MaSP like '" + MaSP1 + "'";
                    }
                    else
                        MessageBox.Show("Nhập sai thông tin sản phẩm");
                }
                string_temp += " order by dbo.Load_CTSP_Mua.TenSP,dbo.Load_CTSP_Mua.TenChiTiet";
                ds = prs.dts(string_temp);
                if (dataGridView6.Rows.Count > 1)
                    dataGridView6.Rows.Clear();
                if (ds.Tables[0].Rows.Count > 0)
                {

                    for (i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        dataGridView6.Rows.Add(ds.Tables[0].Rows[i]["TenSP"].ToString(), ds.Tables[0].Rows[i]["TenChiTiet1"].ToString(), ds.Tables[0].Rows[i]["SLTon"].ToString(), ds.Tables[0].Rows[i]["DBTon"].ToString(), ds.Tables[0].Rows[i]["TenChiTiet"].ToString());
                        // dataGridView6.Rows.Add(ds.Tables[0].Rows[i]["TenSP"].ToString();
                    }
                }
                else
                    MessageBox.Show("Không có dữ liệu, kiểm tra lại thong tin tìm kiếm");
                ds.Clear();
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void bt_searchTK_Click(object sender, EventArgs e)
        {
            TonKho_Tab();
        }
        private void Report_TH()
        {
            Process prs = new Process();
            DataSet ds = new DataSet();
            SqlConnection Conn = prs.Connect();
            Conn.Open();
            SqlCommand cmd = new SqlCommand();
            
            cmd.Connection = Conn;
            cmd.CommandType = CommandType.StoredProcedure;
            try
            {
                string[] temp = txt_NgayStartTH.Text.Split('/');
                Ngay_start1 = temp[1] + "/" + temp[0] + "/" + temp[2] + " 00:00:00";
                string[] temp2 = txt_NgayEndTH.Text.Split('/');
                Ngay_End1 = temp2[1] + "/" + temp2[0] + "/" + temp2[2] + " 23:59:59";
                cmd.CommandText = "prc_KV2XLR_TH_Ngay";
                if (cb_MaSP_reportTH.Text == "")
                {

                    cmd.Parameters.AddWithValue("@datebegin", Ngay_start1);
                    cmd.Parameters.AddWithValue("@dateend", Ngay_End1);
                    cmd.Parameters.AddWithValue("@MaSP", "");
                    cmd.Parameters.AddWithValue("@check", 0);

                }
                if (cb_MaSP_reportTH.Text!="")
                {
                    MaSP1 = prs.substring_right(cb_MaSP_reportTH.Text, child);
                    if (MaSP1 == "")
                        MessageBox.Show("Nhập sai thông tin SP");
                    else
                    {


                        cmd.Parameters.AddWithValue("@datebegin", Ngay_start1);
                        cmd.Parameters.AddWithValue("@dateend", Ngay_End1);
                        cmd.Parameters.AddWithValue("@MaSP", MaSP1);
                        cmd.Parameters.AddWithValue("@check", 1);
                        ds = prs.dts_sql(cmd);

                        /*Search = @"select qry2.MaCT,Load_CTSP_Mua.TenSP,Load_CTSP_Mua.TenChiTiet,Load_CTSP_Mua.SoLuongCT,qry2.SLNhap,qry2.SLNhap/SoLuongCT as DBNhapPS,qry2.SLXuat,qry2.SLXuat/SoLuongCT as DBXuatPS,isnull(qry2.TonDau,0) as TonDau,qry2.TonPS,qry2.TonPS/SoLuongCT as DBTonPS,(qry2.TonPS+isnull(qry2.TonDau,0) )*Load_CTSP_Mua.ChieuDaySC*Load_CTSP_Mua.ChieuRongSC*Load_CTSP_Mua.ChieuDaiSC/1000000000 as SoKhoi
                                from (select MaCT,sum(SLNhap) as SLNhap,sum(SLXuat) as SLXuat,sum(TonDau) as TonDau,sum(TonPS)as TonPS 
                                from((select MaCT,sum(SLNhap) as SLNhap,sum(SLXuat) as SLXuat,sum(SLNhap)-sum(SLXuat) as TonPS,TonDau=0  from dbo.KV1_KTG
                                where Ngay>='" + Ngay_start1 + " 00:00:00' and Ngay<='" + Ngay_End1 + " 23:59:59' Group by MaCT) union all (select MaCT,SLNhap=0,SLXuat=0,TonPS=0,sum(SLNhap)-sum(SLXuat) as TonDau from dbo.KV1_KTG where Ngay<'" + Ngay_start1 + " 00:00:00' group by MaCT)) as qry1 group by MaCT) as qry2 inner join dbo.Load_CTSP_Mua on qry2.MaCT=Load_CTSP_Mua.MaChiTiet where Load_CTSP_Mua.MaSP='" + MaSP1 + "'";*/
                        //Test
                    }
                }
                ds = prs.dts_sql(cmd);
                Fr_Report FrR = new Fr_Report();
                Ngay_start1 = txt_NgayStartTH.Text+" - ";
                Ngay_End1 = txt_NgayEndTH.Text;
                FrR.report_KV2XLR_TH(ds, Ngay_start1, Ngay_End1);
                FrR.Show();
                ds.Clear();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                cmd.Dispose();
                Conn.Close();
            }
        }
        private void KV2XLR_BS()
        {
            Process prs = new Process();
            DataSet ds = new DataSet();
           
            try
            {
                //cmd.CommandType = CommandType.StoredProcedure;
                string[] temp = txt_NgayStartTH.Text.Split('/');
                Ngay_start1 = temp[1] + "/" + temp[0] + "/" + temp[2] + " 00:00:00";
                string[] temp2 = txt_NgayEndTH.Text.Split('/');
                Ngay_End1 = temp2[1] + "/" + temp2[0] + "/" + temp2[2] + " 23:59:59";
                string_temp = @"select dbo.Load_CTSP_Mua.TenSP,dbo.Load_CTSP_Mua.TenChiTiet,qry1.SLXuat as SLXP,qry2.SoLuong,qry1.SLXuat-qry2.SoLuong as SLLP,qry2.SoLuong/qry1.SLXuat*100 as SoKhoi from
                                    (select sum(dbo.KV2_XLR.SLXLR) as SLXuat,KV2_XLR.MaChiTiet from dbo.KV2_XLR
                                    where KV2_XLR.Ngay>='"+Ngay_start1+"' and KV2_XLR.Ngay<='"+Ngay_End1+"' group by MaChiTiet) as qry1";
                string_temp +=@"                    left join (select sum(dbo.KV2_XLR.SLXLR) as SoLuong,KV2_XLR.MaChiTiet from dbo.KV2_XLR
                                    where KV2_XLR.Ngay>='"+Ngay_start1+"' and KV2_XLR.Ngay<='"+Ngay_End1+"' and SoPhieu like 'BS%' group by MaChiTiet) as qry2 on qry1.MaChiTiet=qry2.MaChiTiet inner join dbo.Load_CTSP_Mua on dbo.Load_CTSP_Mua.MaChiTiet=qry1.MaChiTiet";
              
                if (cb_MaSPReport.Text != "")
                {
                    MaSP1 = prs.substring_right(cb_MaSPReport.Text, child);
                    if (MaSP1 == "")
                        MessageBox.Show("Nhập sai thông tin SP");
                    else
                    {


                        string_temp += " and dbo.Load_CTSP_Mua.MaSP='" + MaSP1 + "'";
                        //

                        /*Search = @"select qry2.MaCT,Load_CTSP_Mua.TenSP,Load_CTSP_Mua.TenChiTiet,Load_CTSP_Mua.SoLuongCT,qry2.SLNhap,qry2.SLNhap/SoLuongCT as DBNhapPS,qry2.SLXuat,qry2.SLXuat/SoLuongCT as DBXuatPS,isnull(qry2.TonDau,0) as TonDau,qry2.TonPS,qry2.TonPS/SoLuongCT as DBTonPS,(qry2.TonPS+isnull(qry2.TonDau,0) )*Load_CTSP_Mua.ChieuDaySC*Load_CTSP_Mua.ChieuRongSC*Load_CTSP_Mua.ChieuDaiSC/1000000000 as SoKhoi
                                from (select MaCT,sum(SLNhap) as SLNhap,sum(SLXuat) as SLXuat,sum(TonDau) as TonDau,sum(TonPS)as TonPS 
                                from((select MaCT,sum(SLNhap) as SLNhap,sum(SLXuat) as SLXuat,sum(SLNhap)-sum(SLXuat) as TonPS,TonDau=0  from dbo.KV1_KTG
                                where Ngay>='" + Ngay_start1 + " 00:00:00' and Ngay<='" + Ngay_End1 + " 23:59:59' Group by MaCT) union all (select MaCT,SLNhap=0,SLXuat=0,TonPS=0,sum(SLNhap)-sum(SLXuat) as TonDau from dbo.KV1_KTG where Ngay<'" + Ngay_start1 + " 00:00:00' group by MaCT)) as qry1 group by MaCT) as qry2 inner join dbo.Load_CTSP_Mua on qry2.MaCT=Load_CTSP_Mua.MaChiTiet where Load_CTSP_Mua.MaSP='" + MaSP1 + "'";*/
                        //Test
                    }
                }
                ds = prs.dts(string_temp);
                Fr_Report FrR = new Fr_Report();
                Ngay_start1 = txt_NgayStartTH.Text+" - ";
                Ngay_End1 = txt_NgayEndTH.Text;
                FrR.report_KV2XLR_BS(ds, Ngay_start1, Ngay_End1);
                FrR.Show();
                ds.Clear();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
           
        }
        private void bt_report_TH_Click(object sender, EventArgs e)
        {
            Report_TH();
        }
        private void KV2_XLR_TDKH()
        {
            try
            {
                Process prs = new Process();
                DataSet ds = new DataSet();
                string_temp = "select * from KV2_TDKHXLR";
                ds = prs.dts(string_temp);
                Fr_Report FrR = new Fr_Report();
                FrR.report_KV2XLR_TDKH(ds);
                FrR.Show();
                ds.Clear();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void FrKV2_XP_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Control)
            {
                /*if (e.KeyCode.Equals(Keys.N))
                {
                    rd_GiaoSoChe.Enabled = true;
                    rd_ChuyenNoiBo.Enabled = true;
                }*/
               /* if (e.KeyCode.Equals(Keys.G))
                {
                    maskedTextBox1.Visible = true;
                    maskedTextBox2.Visible = true;
                }*/
                if(e.KeyCode.Equals(Keys.P))
                {
                    Print_PhieuXuat();
                }
            }
        }

        private void txt_Serial_Leave(object sender, EventArgs e)
        {
            Process prs = new Process();
            if (txt_Serial.Text != "")
            {
                string_temp = @"SELECT [Serial],Load_CTSP_Mua.TenSP+' - '+Load_CTSP_Mua.MaSP as MaSP
                              ,Load_CTSP_Mua.TenChiTiet+' - '+Load_CTSP_Mua.MaChiTiet as MaCT
                              ,[SoBB] as SoPhieu
                              ,[SoXe]
                              ,left(SoKH,5)+' - '+replace([SoKH],'KV1X','KV2XP') as SoKH
                          FROM [DataBase_ScansiaPacific2013].[dbo].[KV1_KTG] inner join dbo.Load_CTSP_Mua on Load_CTSP_Mua.MaChiTiet=KV1_KTG.MaCT
                          where Serial=" + txt_Serial.Text;
                try
                {
                    DataSet ds = prs.dts(string_temp);
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        cb_MaSPoutput.Text = ds.Tables[0].Rows[0]["MaSP"].ToString();
                        cb_MaCToutput.Text = ds.Tables[0].Rows[0]["MaCT"].ToString();
                        txt_SoBBoutput.Text = ds.Tables[0].Rows[0]["SoPhieu"].ToString();
                        txt_SoXeoutput.Text = ds.Tables[0].Rows[0]["SoXe"].ToString();
                        cb_SoKHoutput.Text = ds.Tables[0].Rows[0]["SoKH"].ToString();
                        // cb_SoKHoutput.Items.Add(ds.Tables[0].Rows[0]["SoKH"].ToString());
                    }
                    ds.Clear();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }

        }

        private void cb_LyDoXuat_Leave(object sender, EventArgs e)
        {
            if (rd_ChiTiet.Checked == true)
            {
                Process prs = new Process();
                SqlConnection Conn = prs.Connect();
                Conn.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = Conn;
                try
                {
                    if (cb_MaCT.Text != "")
                    {
                        cb_SoPhieuAdd.Items.Clear();
                        MaCT1 = prs.substring_right(cb_MaCT.Text, child);
                        cmd.CommandText = "SELECT TOP 20 left([SoPhieu],5) FROM [dbo].[KV2_XLR] where MaChiTiet='" + MaCT1 + "' order by Serial Desc";
                        SqlDataReader rd = cmd.ExecuteReader();
                        while (rd.Read())
                        {
                            cb_SoPhieuAdd.Items.Add(rd[0].ToString());
                            //cb_MaCT.Items.Add(rd[0].ToString());
                        }
                        //rd.Close();
                        rd.Dispose();
                        txt_SoPhieu.Enabled = false;
                        //cb_SoPhieuAdd.Focus();
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                finally
                {
                    Conn.Close();
                    cmd.Dispose();
                }
            }
            
        }

        private void cb_SoPhieuAdd_SelectedIndexChanged(object sender, EventArgs e)
        {
            txt_SoPhieu.Text = cb_SoPhieuAdd.Text;
        }
        

        private void cb_MaCT_C_SelectedIndexChanged(object sender, EventArgs e)
        {
            Process prs = new Process();
            FormProcess Frp = new FormProcess();
            SqlConnection Conn = prs.Connect();
            SqlCommand cmd = new SqlCommand();
            try
            {
                cb_SoKH_C.Items.Clear();
                cb_SoKH_C.Text = "";
                Conn.Open();
                cmd.Connection = Conn;
                MaCT1 = prs.substring_right(cb_MaCT_C.Text, child);
                string_temp = "Chuyển - Chuyen";
                cb_SoKH_C.Items.Add(string_temp);
                lb_KHC.Text = "10000";
                string_temp = @"select dbo.KV2_TK.SLTon from dbo.KV2_TK where MaChiTiet='" + MaCT1 + "'";
                cmd.CommandText = string_temp;
                lb_TonKho_C.Text = cmd.ExecuteScalar().ToString();
                
            }
            catch
            {
                //MessageBox.Show(ex.Message);
                lb_TonKho.Text = "0";
            }
            finally
            {
                Conn.Close();
                cmd.Dispose();
            }
        }

        private void cb_SoKH_C_Leave(object sender, EventArgs e)
        {
            /*FormProcess Frp = new FormProcess();
            Process prs = new Process();
            SqlConnection Conn = prs.Connect();
            Conn.Open();
            SqlCommand cmd = new SqlCommand();
            try
            {
                SoKH1 = prs.substring_right(cb_SoKH_C.Text, child);
                string check_SL = null;
                check_SL = @"select SLKH-SLTheoDoi from dbo.KH_TheoDoi where ID='" + SoKH1 + "'";
                cmd.CommandText = check_SL;
                cmd.Connection = Conn;
                lb_KHC.Text = cmd.ExecuteScalar().ToString();
            }
            catch
            {
                //MessageBox.Show(ex.Message);
                cb_SoKH_C.Text = "";
                lb_KHC.Text = "0";
            }
            finally
            {
                Conn.Close();
                cmd.Dispose();
            }*/
            lb_KHC.Text = "2000";
        }

        private void cb_MaSP_N_SelectedIndexChanged(object sender, EventArgs e)
        {
            Process prs = new Process();

            MaSP1 = prs.substring_right(cb_MaSP_N.Text, child);
            cb_MaCT_N.Items.Clear();

            cb_MaCT_N.Text = "";
            string sql_load = @"select MaChiTiet,TenChiTiet from dbo.ChiTietSP where MaSP='" + MaSP1 + "'";
            //Data dta = new Data();
            SqlConnection Conn = prs.Connect();
            SqlCommand cmd = new SqlCommand(sql_load, Conn);
            try
            {
                Conn.Open();

                SqlDataReader rd = cmd.ExecuteReader();
                while (rd.Read())
                {
                    cb_MaCT_N.Items.Add(rd[1].ToString() + " - " + rd[0].ToString());
                    //cb.Items.Add(rd[column1].ToString() + " - " + rd[column2].ToString());

                }
                Conn.Close();
                cmd.Dispose();
                rd.Close();
            }
            catch (Exception ex)
            { MessageBox.Show("Lỗi load Combobox " + ex.Message); }
        }

        private void cb_MaCT_N_SelectedIndexChanged(object sender, EventArgs e)
        {
            cb_SoKH_N.Items.Clear();
            lb_KHN.Text = "2000";
            string_temp="Chuyển - Chuyen";
            cb_SoKH_N.Items.Add(string_temp);
            /*Process prs = new Process();
            FormProcess Frp = new FormProcess();
            SqlConnection Conn = prs.Connect();
            SqlCommand cmd = new SqlCommand();
            try
            {
                cb_SoKH_N.Items.Clear();
                cb_SoKH_N.Text = "";
                Conn.Open();
                cmd.Connection = Conn;
                MaCT1 = prs.substring_right(cb_MaCT_N.Text, child);
                string_temp = @"select dbo.KV2_TK.SLTon from dbo.KV2_TK where MaCT='" + MaCT1 + "'";
                cmd.CommandText = string_temp;
                //lb_TonKho_N.Text = cmd.ExecuteScalar().ToString();
                string_temp = @"select left(ID_KeHoach,5),ID from KH_TheoDoi where MaCT='" + MaCT1 + "' and ID_KeHoach like '%KV2XLR%'";
                Frp.cb1(cb_SoKH_N, string_temp, 0, 1);
            }
            catch
            {

                lb_TonKho.Text = "0";
            }
            finally
            {
                Conn.Close();
                cmd.Dispose();
            }*/
        }

        private void cb_SoKH_N_Leave(object sender, EventArgs e)
        {
            lb_KHN.Text = "2000";
            /*FormProcess Frp = new FormProcess();
            Process prs = new Process();
            SqlConnection Conn = prs.Connect();
            Conn.Open();
            SqlCommand cmd = new SqlCommand();
            try
            {
                SoKH1 = prs.substring_right(cb_SoKH_N.Text, child);
                string check_SL = null;
                check_SL = @"select SLTheoDoi from dbo.KH_TheoDoi where ID='" + SoKH1 + "'";
                cmd.CommandText = check_SL;
                cmd.Connection = Conn;
                lb_KHN.Text = cmd.ExecuteScalar().ToString();
            }
            catch
            {
                //MessageBox.Show(ex.Message);
                cb_SoKH_N.Text = "";
                lb_KHN.Text = "0";
            }
            finally
            {
                Conn.Close();
                cmd.Dispose();
            }*/
        }

        private void txt_SLChuyen_Leave(object sender, EventArgs e)
        {
            try
            {
                if (txt_SLChuyen.Text != "")
                {
                    SLNhap_d = double.Parse(txt_SLChuyen.Text);
                    SLKH_N = double.Parse(lb_KHN.Text);
                    double SLKH_C = double.Parse(lb_KHC.Text);
                    double TK_KTG = double.Parse(lb_TonKho_C.Text);
                    if (SLNhap_d > SLKH_N || SLNhap_d > SLKH_C || SLNhap_d > TK_KTG)
                    {

                        MessageBox.Show("Số lượng cần chuyển không được vượt quá " + SLKH_N.ToString() + " hoặc " + SLKH_C.ToString() + " hoặc " + TK_KTG.ToString());
                        txt_SLChuyen.Text = "";
                    }

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void txt_SLChuyen_TextChanged(object sender, EventArgs e)
        {
            FormProcess Frp = new FormProcess();
            Frp.checktext_number(txt_SLChuyen);
        }
        private void add_grid_Trans()
        {
            string TenSP2, TenCT2, MaCT2, SoKH2;
            try
            {
                Process prs = new Process();
                TenSP1 = prs.substring_left(cb_MaSP_C.Text, child);
                TenCT1 = prs.substring_left(cb_MaCT_C.Text, child);
                MaCT1 = prs.substring_right(cb_MaCT_C.Text, child);
                SoKH1 = prs.substring_right(cb_SoKH_C.Text, child);
                TenSP2 = prs.substring_left(cb_MaSP_N.Text, child);
                TenCT2 = prs.substring_left(cb_MaCT_N.Text, child);
                MaCT2 = prs.substring_right(cb_MaCT_N.Text, child);
                SoKH2 = prs.substring_right(cb_SoKH_N.Text, child);

                if (TenSP1 == "" || MaCT1 == "" || txt_SLChuyen.Text == "" || SoKH1 == "" || TenSP2 == "" || MaCT2 == "" || SoKH2 == "")
                {
                    MessageBox.Show("Thông Tin Nhập Không Chính Xác Hoặc Thiếu");
                }
                else
                {
                    i = 0;
                    if (dataGridView7.Rows.Count > 1)
                    {
                        while (i < dataGridView7.Rows.Count - 1)
                        {
                            if (MaCT1 != dataGridView7.Rows[i].Cells["MaCT_C"].Value.ToString())
                                i++;
                            else
                                break;
                        }
                    }
                    if (dataGridView7.Rows.Count == 1 || i == dataGridView7.Rows.Count - 1)
                    {
                        k = cb_MaCT_C.Items.Count - 1;
                        while (k >= 0)
                        {

                            if (MaCT1 == prs.substring_right(cb_MaCT_C.Items[k].ToString(), child))
                                break;
                            else
                                k--;
                        }
                        j = cb_SoKH_C.Items.Count - 1;
                        //MessageBox.Show(j.ToString());
                        while (j >= 0)
                        {
                            if (SoKH1 == prs.substring_right(cb_SoKH_C.Items[j].ToString(), child))
                                break;
                            else
                                j--;
                        }
                        if (k >= 0 && j >= 0)
                        {
                            //SoBB1 = txt_SoBBinput.Text.Trim();
                            //SL1 = txt_SLInput.Text.Trim();
                            Ngay1 = txt_Ngay_C.Text.Trim();
                            SLNhap1 = txt_SLChuyen.Text;
                            string[] temp = txt_Ngay_C.Text.Split('/');
                            NgayInsert1 = temp[1] + "/" + temp[0] + "/" + temp[2];

                            dataGridView7.Rows.Add(TenSP1, MaCT1, TenCT1, SoKH1, SLNhap1, Ngay1, NgayInsert1, "2");
                            SLNhap1 = "-" + txt_SLChuyen.Text;
                            dataGridView7.Rows.Add(TenSP2, MaCT2, TenCT2, SoKH2, SLNhap1, Ngay1, NgayInsert1, "2");
                            j = dataGridView7.Rows.Count - 1;
                            dataGridView7.CurrentCell = dataGridView7.Rows[j].Cells[0];
                            dataGridView7.FirstDisplayedCell = dataGridView7.Rows[j].Cells[0];
                            prs.formatcolordatagrid(dataGridView7);
                            //prs.reset_txt(groupPanel1);
                            txt_SLChuyen.Text = "";
                            lb_KHC.Text = "0";
                            lb_KHN.Text = "0";
                            cb_MaSP_C.Focus();
                            cb_SoKH_C.Text = "";
                            cb_MaSP_N.Text = "";
                            cb_MaCT_C.Text = "";
                            cb_SoKH_N.Text = "";
                        }
                        else
                            MessageBox.Show("Kiểm tra lại Mã CT hoặc Mã KH nhập");
                    }
                    else
                        MessageBox.Show("Chi Tiết này đã có trong DS phía dưới");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void buttonX2_Click(object sender, EventArgs e)
        {
            add_grid_Trans();
        }

        private void buttonX4_Click(object sender, EventArgs e)
        {
            Data dta = new Data();
            SqlConnection Conn = dta.Connect();
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "Tran_Ins_Up_XLR";
            cmd.CommandType = CommandType.StoredProcedure;
            Conn.Open();
            cmd.Connection = Conn;

            try
            {
                UserXuat = "";
                if (dataGridView7.Rows.Count > 1)
                {

                    for (i = dataGridView7.Rows.Count - 2; i >= 0; i--)
                    {
                        //MaCT1 = "'Null'";

                        MaCT1 = dataGridView7.Rows[i].Cells["MaCT_C"].Value.ToString();
                        SoKH1 = dataGridView7.Rows[i].Cells["KH_C"].Value.ToString();

                        SLXuat_d = double.Parse(dataGridView7.Rows[i].Cells["SL_C"].Value.ToString());

                        flag1 = dataGridView7.Rows[i].Cells["flag_C"].Value.ToString();
                        Ngay1 = dataGridView7.Rows[i].Cells["NgayInsert_C"].Value.ToString();
                        string UserNhap = lb_user.Text;
                        //insert_NhapKTG = @"insert into dbo.KV1_KTG(MaCT,SoBB,SoKH,SLNhap,Ngay,UserNhap,GhiChu)values(N'" + MaCT1 + "',N'" + SoBB1 + "',N'" + SoKH1 + "'," + SLNhap_d + ",'" + Ngay1 + "',N'" + UserNhap + "',N'"+GhiChu1+"')";
                        cmd.Parameters.AddWithValue("@MaChiTiet", MaCT1);
                        cmd.Parameters.AddWithValue("@SoPhieu", SoKH1);
                        cmd.Parameters.AddWithValue("@SoXe", "");
                        cmd.Parameters.AddWithValue("@SLXLR", SLXuat_d);
                        cmd.Parameters.AddWithValue("@LyDoXuat", "Chuyen");
                        cmd.Parameters.AddWithValue("@Ngay", Ngay1);
                        cmd.Parameters.AddWithValue("@GhiChu", "Chuyen");
                        cmd.Parameters.AddWithValue("@UserXLR", UserXuat);
                        cmd.ExecuteNonQuery();
                        cmd.Parameters.Clear();
                        dataGridView7.Rows.RemoveAt(i);

                    }
                    MessageBox.Show("Dữ Liệu được lưu thành công");
                    lb_Tong.Text = "0";
                    dta.reset_txt(groupPanel1);
                    cb_MaCT_C.Text = "";
                    cb_MaSP_C.Text = "";
                    cb_MaSP_N.Text = "";
                    cb_MaCT_N.Text = "";
                    cb_SoKH_C.Text = "";
                    cb_SoKH_N.Text = "";
                    cb_MaSP_C.Focus();
                }



            }
            catch (Exception ex)
            {
                string s = "insert duplicate key";
                string FK = "FOREIGN KEY constraint";
                string s1 = ex.Message.ToString();
                if (s1.Contains(s))
                { MessageBox.Show("Insert không thành công \n" + "Mã đã tồn tại "); }
                else if (s1.Contains(FK))
                { MessageBox.Show("Nhập sai thông tin trong Combobox"); }
                else
                    MessageBox.Show(ex.Message);
                MessageBox.Show("Đã xảy ra lỗi khi thêm dữ liệu, vui lòng kiểm tra lại");
            }
            finally
            {
                Conn.Close();
                cmd.Dispose();
            }
        }

        private void cb_MaSP_C_SelectedIndexChanged(object sender, EventArgs e)
        {
            Process prs = new Process();

            MaSP1 = prs.substring_right(cb_MaSP_C.Text, child);
            cb_MaCT_C.Items.Clear();

            cb_MaCT_C.Text = "";
            string sql_load = @"select MaChiTiet,TenChiTiet from dbo.ChiTietSP where MaSP='" + MaSP1 + "'";
            //Data dta = new Data();
            SqlConnection Conn = prs.Connect();
            SqlCommand cmd = new SqlCommand(sql_load, Conn);
            try
            {
                Conn.Open();

                SqlDataReader rd = cmd.ExecuteReader();
                while (rd.Read())
                {
                    cb_MaCT_C.Items.Add(rd[1].ToString() + " - " + rd[0].ToString());
                    //cb.Items.Add(rd[column1].ToString() + " - " + rd[column2].ToString());

                }
                Conn.Close();
                cmd.Dispose();
                rd.Close();
            }
            catch (Exception ex)
            { MessageBox.Show("Lỗi load Combobox " + ex.Message); }
            
        }

        private void tab_BangKe_Click(object sender, EventArgs e)
        {
            Data dta = new Data();
            SqlConnection Conn = dta.Connect();
            DataSet ds = new DataSet();
            if (dataGridView11.Rows.Count > 1)
                dataGridView11.Rows.Clear();
            try
            {
                string[] temp = txt_NgayBK.Text.Split('/');
                Ngay1 = temp[1] + "/" + temp[0] + "/" + temp[2];
                string_temp = @"select Load_CTSP_Mua.TenSP,Load_CTSP_Mua.MaChiTiet,Load_CTSP_Mua.TenChiTiet,qry1.* 
                                      from ( 
                                            SELECT  [Serial]
                                          ,[MaChiTiet]
                                          ,[SoKH]
                                          ,[Serial_link]
                                          ,cast([SoPhieu] as varchar) as SoPhieu
                                          ,[SoXe]
                                          ,[SLXP]
                                          ,SLXLR=0
                                          ,convert(varchar(10),[NgayXP],103) as Ngay
                                          ,[GhiChu]
                                          ,'' as LyDo
                                          ,[NgayInsert]
                                      FROM [dbo].[KV2_LXP] where NgayInsert>='" +Ngay1+" 00:00' and NgayInsert<='"+Ngay1+" 23:59'";
                string_temp +=@"                      Union all
                                      SELECT [Serial]
                                          ,[MaChiTiet]
                                          ,'' as SoKH
      
                                          ,'' as Serial_link
                                          ,[SoPhieu]
                                          ,SoXe
                                          ,SLXP=0
                                          ,[SLXLR]
      
                                          ,convert(varchar(10),[Ngay],103) as Ngay
                                          ,[GhiChu]
                                          ,[LyDoXuat] as LyDo
                                          ,[NgayInsert]
                                      FROM [dbo].[KV2_XLR] where NgayInsert>='" +Ngay1 + " 00:00' and NgayInsert<='" + Ngay1 + " 23:59') as qry1 inner join dbo.Load_CTSP_Mua on dbo.Load_CTSP_Mua.MaChiTiet=qry1.MaChiTiet";
                //MessageBox.Show(string_temp);
                ds = dta.dts(string_temp);
               // MessageBox.Show(string_temp);
                if (ds.Tables[0].Rows.Count > 0)
                {
                    for (i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        dataGridView11.Rows.Add(ds.Tables[0].Rows[i]["TenSP"].ToString(), ds.Tables[0].Rows[i]["MaChiTiet"].ToString(), ds.Tables[0].Rows[i]["TenChiTiet"].ToString(), ds.Tables[0].Rows[i]["Serial_link"].ToString(), ds.Tables[0].Rows[i]["SoPhieu"].ToString(),  ds.Tables[0].Rows[i]["SoKH"].ToString(),ds.Tables[0].Rows[i]["SLXP"].ToString(), ds.Tables[0].Rows[i]["SLXLR"].ToString(), ds.Tables[0].Rows[i]["Ngay"].ToString(), ds.Tables[0].Rows[i]["NgayInsert"].ToString(), ds.Tables[0].Rows[i]["SoXe"].ToString(), ds.Tables[0].Rows[i]["GhiChu"].ToString(),ds.Tables[0].Rows[i]["Serial"].ToString());
                        dataGridView11.Rows[i].HeaderCell.Value = (i + 1).ToString();
                    }

                    ds.Clear();
                    for (i = dataGridView11.Rows.Count - 2; i >= 0; i--)
                    {
                        if (dataGridView11.Rows[i].Cells["SLNhapBK"].Value.ToString() == "0")
                            dataGridView11.Rows[i].DefaultCellStyle.BackColor = Color.AliceBlue;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void txt_Serial_DoubleClick(object sender, EventArgs e)
        {
            if (cb_MaCToutput.Text != "")
            {
                Process prs = new Process();
                MaCT1 = prs.substring_right(cb_MaCToutput.Text, child);
                if (MaCT1 != "")
                {
                    DataSet ds = new DataSet();
                    string_temp = @"select LP.MaCT,LP.Serial as Serial_KV2,LP.SLXuat-XP.SLXP as SLCL from (select dbo.KV1_KTG.Serial,dbo.KV1_KTG.SLXuat,MaCT from dbo.KV1_KTG where SLXuat>0 and MaCT='" + MaCT1 + "') as LP";
                    string_temp += @"            inner join (select dbo.KV2_LXP.Serial_link,SUM(KV2_LXP.SLXP) as SLXP from dbo.KV2_LXP group by Serial_link) as XP on LP.Serial=XP.Serial_link order by (LP.SLXuat-XP.SLXP) desc";
                    ds = prs.dts(string_temp);
                    
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        FrGridview fr = new FrGridview(this);
                        /*FrMain FrM = this.MdiParent as FrMain;
                        */
                        fr.Show();
                        fr.datagrid(ds.Tables[0]);
                    }
                }
                
                
            }
            else
                MessageBox.Show("Cho biết tên chi tiết");
        }
        public void Serial_get(string temp)
        {
            //MessageBox.Show(temp);
            txt_Serial.Text = temp;
        }
        //public delegate void SendMessage(string Message);
        //public SendMessage Sender;
      
    }
}
